How to mock final classes inside Android Instrumented Test cases, that is mocking final classes inside Android Run Time?
(I am using Mockito 2.X)
I have a test case like follows -
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import android.util.Log;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
#RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
// This is my app specific NON - Final class
private ShutdownServicesReqSig rebootSig = ShutdownServicesReqSig.newBuilder(ShutDownType.REBOOT_SYSTEM).setReason("test").build();
private PowerManager mockedPowerManager = null;
private Context mockedContext = null;
#Test
public void testRestart() throws InterruptedException
{
mockedContext = Mockito.mock(Context.class);
mockedPowerManager = Mockito.mock(PowerManager.class); // Here is the problem android.os.PowerManager is a Final class in latest Android SDK
// I need to mock it, only then I can use Mockito.verify() on PowerManager
Mockito.when(mockedContext.getSystemService(Context.POWER_SERVICE)).thenReturn(mockedPowerManager);
assertTrue(executor.requestShutdown(rebootSig));
Thread.sleep(1000);
Mockito.verify(mockedPowerManager).reboot(any(String.class)); // Mocking of PowerManager is essential to be sure of method call on PowerManager, using Mockito.verify
Mockito.reset(mockedPowerManager);
}
}
When I am running it as Android Instrumented Test on ART(placing inside - MyApplication\app\src\androidTest), I am getting following error -
org.mockito.exceptions.base.MockitoException:
Cannot mock/spy class android.os.PowerManager
Mockito cannot mock/spy following:
- final classes
- anonymous classes
- primitive types
But, the same code, when I am running as a normal JUnit test, inside JVM (placing inside - MyApplication\app\src\test) it is working perfectly fine.
I need to run it inside ART, as I like to test some of my customized Android Services, and I need to mock final classes like PowerManager, as only then I can use Mockito.verify() on PowerManager, to verify certain method calls on PowerManager.
Help/guides are appreciated.
Mockito 2 has an "opt-in" mechanism to enable mocking of final methods or classes, see here. You enable it via the mockito extension mechanism by creating the file src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker containing a single line:
mock-maker-inline
(well, that file needs to be in the class path).
If that works for you, perfect. If not, there is probably nothing else you can do.
You see, instrumenting boils down to: manipulating byte code. Typically, it doesn't work out to use more than one framework doing that.
Meaning: in order to enable that kind of mocking, bytecode needs to be manipulated. And for obvious reasons, getting two different bytecode manipulation frameworks to nicely coexist is a very tough challenge.
Long story short: try that extension mechanism, when it doesn't work you have to step back and ask yourself: what exactly is the final goal I intend to achieve?!
Most likely, you probably shouldn't waste your time trying to mock things running within ART.
In order to mock and spy final classes & methods in Android Integration tests and Android Instrumentation tests, you need to only add the following dependency to your build.gradle file:
androidTestImplementation "com.linkedin.dexmaker:dexmaker-mockito-inline-extended:2.28.1"
Make sure to remove any other mockito dependency that you are using as an androidTestImplementation.
Also, if you have created a mockito-extensions/org.mockito.plugins.MockMaker file, make sure to delete that either.
This dependecy works for devices running Android P or above.
Refer to these to links for more details on this dependency: Link1, Link2.
Related
I have an application I want to test:
import foo.ExtClass;
public class App {
public static void main(String[] args) {
ExtClass ext = new ExtClass();
...
}
}
I want to write a unit test for this application, however I do not want to use the foo.ExtClass, but use another mock implementation for the class.
Normally I would use a factory to instantiate the class according to some configuration that can be controlled in the unit test.
However, in this case, I cannot modify the tested app.
I was thinking in the direction of writing a custom class loader to load the mock class instead of the real class - not sure if this is possible without any modification to the tested app, and how.
As an option you can use custom classloader, which will substite your class with a testing one. So basically instead of loading ExtClass from your app package, your classloader will load the same class from your testing package with the mock implementation.
Here is an example:
How to replace classes in a running application in java ?
Also there is very usefull tutorial: https://zeroturnaround.com/rebellabs/reloading-objects-classes-classloaders/
The approach I finally used:
Created a separate project with my mock implementation of foo.ExtClass,
and the unit tests.
This way the mock implementation appeared in the classpath before the real implementation, and the original (tested) project remained untouched.
I've got a utility class that I've created:
package com.g2.quizification.utils;
import com.g2.quizification.domain.Question;
public class ParsingUtils {
public static Question parse(String raw) {
Question question = new Question();
//TODO: parse some stuff
return question;
}
}
...that lives here:
I've also followed the tutorials and created a testing app, that looks like this:
And here's my test code, just waiting for some good 'ole TDD:
package com.g2.quizification.utils.test;
import com.g2.quizification.domain.Question;
import com.g2.quizification.utils.ParsingUtils;
public class ParsingUtilsTest {
public void testParse() {
String raw = "Q:Question? A:Answer.";
Question question = ParsingUtils.parse(raw);
//assertEquals("Question?", question.getQuestion());
//assertEquals("Answer.", question.getAnswer());
}
}
The test class is obviously missing the extension, but all the examples seem to only show extending something like ActivityUnitTestCase. I'm not testing an activity; I just want to test a static method in a utility class. Is that possible?
It seems like creating a utility test class should be simple, but I'm not sure what the next step is and/or what I'm missing.
The best approach for test project is to add the test project so that its root directory tests/ is at the same level as the src/ directory of the main application's project. If you are using junit4 and eclipse, you can just right-click on the util class you want to test and choose New -> JUnit Test Case.
Basically I would expect a new test class named ParsingUtilTest under the source folder tests/ and within the package com.g2.quizification.utils.test. The test class should extend TestCase and each method you want to test in that util class should have a new method in the test class with the name preceded with "test". I mean to say, suppose you have a method name in ParsingUtils called parseXml. The test method name in ParsingUtilsTest (which Extend 'TestCase') should be named testParseXml
The test class is obviously missing the extension, but all the examples seem to only show extending something like ActivityUnitTestCase. I'm not testing an activity; I just want to test a static method in a utility class. Is that possible?
Yes, as long as the class your are testing has nothing to do with android apis. And if you do need to test code with android api dependencies, for example, testing a view or an activity, you might want to have a try with robolectric. It's faster than the ones that extend ActivityUnitTestCase.
I have been playing with robolectric a lot (to do TDD on android), and so far, I prefer version 1.1 or 1.2 to 2.x, more stable and run fast.
Besides the tools mentioned above, there are many practices for writing good test cases, naming conventions, code refactoring and such.
It seems like creating a utility test class should be simple, but I'm not sure what the next step is and/or what I'm missing.
Its good to begin with small steps, xUnit Test Patterns: Refactoring Test Code and Extreme Programming Explained are some good books for your reference.
For some reason I fail to follow a pretty straight forward PowerMock example.
I included powermock-mockito-1.5.1-full in my classpath, and I try to test a public final method (following this example).
For some reason I am not able to make the import to the PowerMock class.
import org.junit.*;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.cleancode.lifesaver.camera.*;
#RunWith(PowerMockRunner.class)
#PrepareForTest(android.hardware.Camera.class)
public class CameraTests {
private android.hardware.Camera _cameraMock;
#Before
public void setUp() {
_cameraMock = PowerMockito.mock(android.hardware.Camera.class);
}
#Test
public void releaseCamera() {
ICamera camera = new Camera(_cameraMock);
// Compile error: PowerMock can't be resolved
PowerMock.replay(_cameraMock);
// I also tried PowerMockito.replay(_cameraMock) but that also doesn't exist.
camera.release();
Mockito.verify(_cameraMock).release();
}
}
As the comment explains, the PowerMock class can't be imported from the power mock jar.
It feels like a silly question, but I really can't find anything on the internet.
Where should I be able to find the static class PowerMock? I also used Java Decompile to search the powermock library, no hits on powermock / replay.
The example you are following PowerMock.replay(_cameraMock); is using EasyMock, while you seem to be wanting Mockito. Take a look at this tutorial for mockito & power mock
I suggest you not to create your mock in your setUp() (Before) method, because a mock is very complicated, for example you can tell it exactly how many time it should expect a method is called, if you declare a "general" mock for all your tests it's very difficult to control this behaviour.
maybe (without the code I can only guess) you want that your android.hardware.Camera is called inside your Camera.release() method, am I right? so I whould do like this:
The method you are trying to mock is not static, it's a normal final method. You can try to do this:
android.hardware.Camera mock = PowerMock.createMock(android.hardware.Camera.class);
PowerMock.expect(mock.release());
PowerMock.replay();
ICamera camera = new Camera(mock);
camera.release();
PowerMock.verify(mock);
if inside camera.relase() is not called exactly once the android.hardware.Camera.release() method the test fails.
package com.fitaxis.test;
import java.sql.SQLException;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import static org.mockito.Mockito.*;
import com.fitaxis.leaderboard.LeaderBoard;
public class LeaderBoardTests {
#Test
public void TestThatDataIsSavedToTheDatabase()
{
LeaderBoard leaderBoard = mock(LeaderBoard.class);
//doNothing().doThrow(new RuntimeException()).when(leaderBoard).saveData();
when(leaderBoard.saveData()).thenReturn(true);
boolean res = leaderBoard.saveData();
verify(leaderBoard).saveData();
Assert.assertTrue(res);
}
}
I have used mockito to mock a class, but when I use code coverage it does not detect that the method as been called. Am I doing something wrong? Please help!
It looks like you're mocking out the only call you're making to production code.
In other words, your test says:
When I call saveData(), fake the result to return true
Now call saveData() - yay, the result was true!
None of your production code is being calls at all, as far as I can see.
The point of mocking is to mock out dependencies from your production class, or (sometimes, though I prefer not to) to mock out some methods of your production class that the code you're actually testing will call.
You should probably be mocking out the dependencies of Leaderboard rather than Leaderboard itself. If you must mock out saveData(), you should be testing the methods that call saveData()... check that they save the right data, that they act correctly when saveData() returns false, etc.
if i understand your question correctly :
because you are mocking LeaderBoard. that means that you are not testing it.
if you want to test LeaderBoard, you should test the actual class not the mocked one.
let say you want to test class A but this class depends on B and B is a bit difficult to instantiate in testing environment(for any reason). in such cases you can mock B.
but here is your case you are mocking class A itself. that means you are not testing anything.
add runner class as MockitoJUnitRunner, please refer the below sample code
import org.mockito.junit.MockitoJUnitRunner
#RunWith(MockitoJUnitRunner.class)
public class MockitTesterClass{
#Mock
private TestService testServiceMock;
}
now the code coverage will increase
What I have right now
I have a 3rd party singleton instance that my class under test relies on and that singleton is using System.getenv(String) in its constructor. Is it possible to mock this call?
I tried this
JMockIt Example
new Expectations()
{
System mockedSystem;
{
System.getenv( "FISSK_CONFIG_HOME" ); returns( "." );
}
};
But it gives me an EXCEPTION_ACCESS_VIOLATION and crashes the JVM.
Is there another way to set a system environment variable for a unit test?
In this case you need to use partial mocking so that JMockit doesn't redefine everything in the System class. The following test will pass:
#Test
public void mockSystemGetenvMethod()
{
new Expectations()
{
#Mocked("getenv") System mockedSystem;
{
System.getenv("envVar"); returns(".");
}
};
assertEquals(".", System.getenv("envVar"));
}
I will soon implement an enhancement so that issues like this don't occur when mocking JRE classes. It should be available in release 0.992 or 0.993.
PowerMock seams to be able to mock system classes.
Your other option (assuming you are not unit testing the 3rd party API) is to create a for Facade the 3rd party API that has a nice, easy mockable interface and have your test classes use this rather than the real thing.
Oh, JMockIt supports this too:
package playtest;
import static org.junit.Assert.*;
import mockit.*;
import mockit.integration.junit4.JMockit;
import org.junit.*;
import org.junit.runner.RunWith;
#RunWith(JMockit.class)
public class JMockItTest {
#Test
public void mockSystemGetEnv() {
Mockit.setUpMocks(MockSystem.class);
assertEquals("Bye", System.getenv("Hello"));
}
#MockClass(realClass = System.class)
public static class MockSystem {
#Mock
public static String getenv(String str) {
return "Bye";
}
}
}
You can't change the environment but you can change the access to it: Simply wrap the call to System.getenv() in a method or a helper class and then mock that.
[EDIT] Now your problem is how to change the code of your third party library. The solution here is to use a Java decompiler and to fix the class. If you want, you can send in a feature request in, too. Add that new class to your test suite. That should make your IDE find the class for the tests.
Since test code doesn't go into production, you can run your tests and the production code will use the original library.
A while back I wanted to test System.exit, and found a solution by using a custom SecurityManager. You can verify the call is being made, and the argument of the call, but using this method, you can't mock the return value of the call.
An update on #Rogério answer.
In my case with JMockit 1.25 I had to do it using the MockUp API:
#Test
public void mockSystemGetenvMethod(){
new MockUp<System>()
{
#Mock
public String getenv(final String string) {
return "";
}
};
assertEquals(".", System.getenv("envVar"));
}