0

I am getting

java.lang.NullPointerException
    at android.content.ComponentName.__constructor__(ComponentName.java:131)

because during unit test the class is not being found even though the package name is correct.

This is the method I am trying to test:

fun mainActivityIntentProvider(): Intent {
        var myClass: Class<*>? = null
        try {
            myClass = Class.forName("packageName.MyMainActivity")
        } catch (e: ClassNotFoundException) {
            // Some logging statement stating class not found
        }
        return Intent(AppContextHolder.getAppContext(), myClass)
    }

The unit test code that I have written (using MockK):

@Test
    fun testMainActivityIntentProviderInHelper() {
        context = mockk<Context>(relaxed = true)

        every { AppContextHolder.getAppContext() } returns context
        val expectedClassName = "packageName.MyMainActivity"

        val result = myDemoClass.mainActivityIntentProvider()
        val className = result.component?.className
        assertEquals(expectedClassName, className)
    }
Abra
  • 19,142
  • 7
  • 29
  • 41
MChak
  • 25
  • 6
  • The package name may be correct, but [ClassNotFoundException](https://developer.android.com/reference/java/lang/ClassNotFoundException) means that the class (`packageName.MyMainActivity` ?) is not on the CLASSPATH. Enter `[android] classpath` into the search box at the top of this webpage. The `NullPointerException` is thrown because you simply log the `ClassNotFoundException` which means essentially that you ignore it. Hence `NullPointerException` is **not** the problem. – Abra Jun 15 '23 at 04:52
  • @Abra when I put the debugger I saw myClass is appearing null. – MChak Jun 16 '23 at 12:32
  • `Class.forName("packageName.MyMainActivity")` is throwing an exception, hence `myClass` is not being assigned a value. – Abra Jun 16 '23 at 13:14

0 Answers0