How to mock MainActivity using Mockito or another mocking framework?

104 Views Asked by At

I need to mock MainActivity as it is a parameter of an unit test I have. I tried private val mockMainActivity: MainActivity = mock(). However I get:

Mockito cannot mock this class: class se.username.mmi.onboard.activities.MainActivity.

Java : 11 JVM vendor name : JetBrains s.r.o. JVM vendor version : 11.0.15+0-b2043.56-8887301 JVM name : OpenJDK 64-Bit Server VM JVM version : 11.0.15+0-b2043.56-8887301 JVM info : mixed mode OS name : Linux OS version : 6.2.0-31-generic

You are seeing this disclaimer because Mockito is configured to create inlined mocks. You can learn about inline mocks and their limitations under item #39 of the Mockito class javadoc.

Underlying exception : java.lang.IllegalArgumentException: Could not create type org.mockito.exceptions.base.MockitoException: Mockito cannot mock this class: class se.username.mmi.onboard.activities.MainActivity.

If you're not sure why you're getting this error, please open an issue on GitHub.

How can I mock MainActivity then?

1

There are 1 best solutions below

1
maulzey On

In your unit test, you can then create a mock or a fake implementation of the MainActivity and pass it to SomeClass. This way, you're testing the logic in SomeClass without worrying about the complexities of MainActivity.

@Test 
fun testSomeClass() { 
val mockMainActivity = mock(MainActivity::class.java) 
val someClass = SomeClass(mockMainActivity) // Test the behavior of SomeClass }