I have a testclass where I am running Mockito tests, like:
public class ViewModelTest {
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
#Test
public void openQuestion() {
viewModel.openQuestion(context, QUESTION_ID);
verify(questionRouter).open(context, QUESTION_ID); //just an example
}
}
Everything is working as should. However, I have to mock a static method in one of my test classes, so I add PowerMock to my class:
#RunWith(PowerMockRunner.class)
#PrepareForTest(Uri.class)
public class ViewModelTest { ...
and dependencies:
testImplementation 'org.powermock:powermock-core:2.0.2'
testImplementation 'org.powermock:powermock-api-mockito2:2.0.2'
testImplementation 'org.powermock:powermock-module-junit4-rule-agent:2.0.2'
testImplementation 'org.powermock:powermock-module-junit4-rule:2.0.2'
testImplementation 'org.powermock:powermock-module-junit4:2.0.2'
But when I now try to run the tests (let's say I have 15 test methods) I get NPE on most test methods:
java.lang.NullPointerException
at com.example.Viewmodel.prepare(StartViewModel.java:126)
I get NPE even in the method where I try to mock the static method:
PowerMockito.mockStatic(Uri.class);
PowerMockito.when(Uri.parse(anyString())).thenReturn(otherUri);
Before you downvote&vote to close for NPE, I have really looked at most answers in SO and other sites, tried many of them which of none worked for me. I followed tutorials for Powermock but I still get this errors, and I do not understand why. This is my last resort to try to solve this.
you are doing the test with the right way, just replace
PowerMockito.when(Uri.parse(anyString())).thenReturn(otherUri);
with when of Mockito
Mockito.when(Uri.parse(anyString())).thenReturn(otherUri);
and add this file https://gist.github.com/badr-ghazouan/1edbed170ce968ef0011f2721911ffc6 to the resource folder under test folder, mockito will load it automatically without doing anything.
Hope this works for you
Related
I am in the process of migrating to kotlin coroutines test 1.6.x
This is a very basic test that fails:
import kotlinx.coroutines.test.runTest
import org.junit.Test
class HouseDaoTest {
#Test
fun insertAndGetHouseFromDb_success() = runTest {
assert(1 == 1)
assert(2 == 2)
}
}
The error message I get when running this test is:
No virtual method find(Lkotlin/jvm/functions/Function1;)Lkotlinx/coroutines/internal/ThreadSafeHeapNode; in class Lkotlinx/coroutines/internal/ThreadSafeHeap; or its super classes (declaration of 'kotlinx.coroutines.internal.ThreadSafeHeap' appears in /data/app/~~rVhSG062Jzg60YKAgWe6uQ==/my.packagename.test-Up28py4pbfA6CKyThEVObA==/base.apk)
The line of code that hold the find method can be found here:
https://github.com/Kotlin/kotlinx.coroutines/blob/81e17dd37003a7105e542eb725f51ee0dc353354/kotlinx-coroutines-test/common/src/TestCoroutineScheduler.kt#L262
But I have honestly no clue what I am doing wrong, since this test is as basic as it gets. I found another SO post with this issue and it mentions that downgrading to 1.6.0 works, but not for me.
I also posted an issue in the respetive gihub: https://github.com/Kotlin/kotlinx.coroutines/issues/3503
Got it and I feel stupid. The tests did not have access to the coroutine-core module.
I now set it up like this:
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4"
androidTestImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.4'
I'm new in writing android unit tests and faced with a problem of injecting some mock dependencies into my test class. I found a lot of articles how I can do it using "old" Dagger (version < 2.10), but nothing about Dagger with version > 2.10. I just want to write smth like that
#RunWith(JUnit4.class)
public class ConfigurationUnitTest {
#Inject SomeDependency someDependency;
public ConfigurationUnitTest() {
}
#Test
public void test() {
//use someDependency variable here
}
}
But I didn't find any way to inject some dependencies into this Test class. Hope someone helps me. Thanks.
I have a problem with Mockito. I have written tests for my presentation layer. I used mockito to mock some dependencies. Everything was working fin for last 2 months and suddenly I started receiving an exception:
java.lang.NoClassDefFoundError: Landroid/content/SharedPreferences;
Previously there were no problem with it at all. I have not changed the version of Mockito and JUnit in my gradle and it looks like:
testCompile "org.mockito:mockito-core:2.+"
testCompile 'junit:junit:4.12'
And my test class looks like:
#RunWith(MockitoJUnitRunner.class)
public class PostDetailsPresenterTest {
#Mock
SharedPreferences preferences;
#Before
public void setUp() {
SharedPrefsUtils utils = new SharedPrefsUtils(preferences);
}
}
But after starting tests I keep receiving an exception. Does someone had similar problem and know how to deal with it?
Try to clean and rebuild. Then ./gradlew clean test. If that doesn't help, remove the .gradle folder from your project and rebuild.
I saw that I'm not the only one having this problem but I don't find a correct answer.
I have an android project that I want to test. I create a junit test class for each class of my project.
My problem is when I run my test, I have the following error :
java.lang.NoClassDefFoundError: android/content/Context
This is my class test :
public class DevicesBDDTest extends TestCase {
DevicesBDD bdd;
/**
* #throws java.lang.Exception
*/
protected static void setUpBeforeClass() throws Exception {
}
/**
* #throws java.lang.Exception
*/
protected static void tearDownAfterClass() throws Exception {
}
protected void setUp() throws Exception {
super.setUp();
Context ctx = mock(Context.class);
final MaBaseSQLiteInterface mockMaBaseSQLite = mock(MaBaseSQLiteInterface.class);
bdd = new DevicesBDD(ctx){
#Override
public MaBaseSQLiteInterface createMaBaseSQlite(Context context) {
return mockMaBaseSQLite;
}
};
}
protected void tearDown() throws Exception {
super.tearDown();
}
public void test() {
assertEquals(1, 1);
}
}
My class DevicesBDD has needs an object Context, therefore I create a mock (with mockito). I tried with a object MockContext too, but it's doesn't work.
This is my Java Build Path :
mockito-all-1.9.5.jar
Android 2.1
-> android.jar
Android Dependencies
-> annotations.jar
Junit 3
-> junit.jar
Not sure if I had the same problem as you but I am using gradle and for some reason the tests just wouldn't run anymore, with the same error as you had. I tried cleaning and rebuilding but to no avail. After hours of frustration and trying to find an answer I came across the simple solution in a GitHub thread:
I resolved this issue by removing the .gradle folder in my project and rebuilding the project.
(thanks to vpetrov)
You can run ./gradlew clean test in the terminal.
Fixed the issue by following these steps --
1.Open module level build.gradle file, go to dependencies, go to this line --
testImplementation 'junit:junit:4.12'
2.Change the junit version to anything else below it (like 4.10)
testImplementation 'junit:junit:4.10'
3.Sync project
4.The issue fixed at this point in my case
5.Set the junit version back to what it was before (4.12 in my case) if you want
testImplementation 'junit:junit:4.12'
6.Sync project
Changing the junit version and syncing project worked in my case.
Robolectric version 4.4 seems not to support jdk 14. So I could switch to jdk 13 or update robolectric to 4.5-alpha-1
Like many others I was excited to hear that Mockito now works with Android and followed this tutorial to see it with my own eyes. Everything seemed fan-flapping-tastic and I got underway incorporating the mocking solution into my Android Test Project...
The error
However, on setting up my application's test project to leverage the mockito-all-1.9.5, dexmaker-1.0 and dexmaker-mockito-1.0 jars I encountered a problem with my very first test case. Precisely this problem in fact. The part that I would like assistance on is;
Caused by: java.lang.VerifyError: org/mockito/cglib/core/ReflectUtils
at org.mockito.cglib.core.KeyFactory$Generator.generateClass(KeyFactory.java:167)
at org.mockito.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
at org.mockito.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:217)
at org.mockito.cglib.core.KeyFactory$Generator.create(KeyFactory.java:145)
at org.mockito.cglib.core.KeyFactory.create(KeyFactory.java:117)
at org.mockito.cglib.core.KeyFactory.create(KeyFactory.java:109)
at org.mockito.cglib.core.KeyFactory.create(KeyFactory.java:105)
at org.mockito.cglib.proxy.Enhancer.<clinit>(Enhancer.java:70)
I have been informed that this "simply doesn't quite work yet" since the stack trace implies that the DexMaker jar is not being used - reference this response. However, I am suspicious that I am doing something wrong with respect to my project set-up so I'm looking to draw from the collective knowledge base here to see if indeed this is user error or a beta-bug.
My Android Test Project set-up
Please find below a screenshot of my test project's configuration. The project was created via the Android Wizard and shares no special features other than the inclusion of the Mockito and DexMaker jars (mentioned above) under the libs directory.
The Test
Never mind the content of the test (the test fails before the unit test is executed) the set-up is as described below;
public class TestSpotRatingCalculator extends InstrumentationTestCase {
#Mock
private AService aService; // Changed the service names being used here - not important.
#Mock
private BService bService;
#Mock
private CService cService;
#Mock
private DService dService;
/**
* #see android.test.AndroidTestCase#setUp()
*/
#Override
protected void setUp() throws Exception {
super.setUp();
MockitoAnnotations.initMocks(this); // Failure here with aforementioned stacktrace...
}
If anyone out there has an idea what is wrong then please sound-off here.
Hi I had the same problem and I found this article really usefull!
http://corner.squareup.com/2012/10/mockito-android.html
The key piece of information is:
To use Mockito on a device or emulator, you’ll need to add three .jar
files to your test project’s libs directory: mockito-all-1.9.5.jar,
dexmaker-1.0.jar, and dexmaker-mockito-1.0.jar.
Just add this in your gradle:
androidTestCompile 'org.mockito:mockito-core:1.10.8'
androidTestCompile 'com.google.dexmaker:dexmaker-mockito:1.1'
We just had the same problem in a project, but our tests also failed on a real device.
The cause was tracked to how Mockito uses the class loader, and resulted in the following error in LogCat:
W/ActivityThread(5777): ClassLoader.getResources: The class loader returned by Thread.getContextClassLoader() may fail for processes that host multiple applications. You should explicitly specify a context class loader. For example: Thread.setContextClassLoader(getClass().getClassLoader());
The fix was to explicitly set the class loader before calling mock() a test, eg.
#Override
protected void setUp() throws Exception {
super.setUp();
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
fooImpl = mock(Foo.class)
}
The problematic file in Mockito is this one: org.mockito.internal.configuration.ClassPathLoader (line 121 in 1.9.5)
As hinted at here the dexmaker-android combo only works 100% when the instrumented tests are run against a real device.
Running the tests against a real device do not exhibit this failure.
For everybody who still have this error, check if you didn't exclude a class in the dependecies. We exluded by accident the MockMaker.class so this was then the cause for the exception.