Robolectric unit testing fails with error message java.lang.RuntimeException: android.content.pm.PackageParser$PackageParserException: Failed to parse {projectDir}/build/intermediates/apk_for_local_test/debugUnitTest/apk-for-local-test.ap_,
Caused by: java.lang.NullPointerException
I started writing unit tests for my application using Robolectric in multi-dynamic feature application, I also just got a fair grip of dynamic feature modules and how best to share dependencies among them. Below is how I solved it.
The problem is that a viewMoel factory dependency common to all which is inject by dagger resides in the library module and a viewModel unit test class resides in the DynamicFeat-1 always fails with error java.lang.RuntimeException: android.content.pm.PackageParser$PackageParserException: Failed to parse {projectDir}/build/intermediates/apk_for_local_test/debugUnitTest/apk-for-local-test.ap_
And the unit test base class
abstract class BaseTest {
lateinit var mockServer: MockWebServer
@Inject
lateinit var factory: ViewModelProviderFactory
@Before
open fun setUp(){
setUpMockServer()
configureDI()
}
@After
open fun tearDown(){
if(isMockServerEnabled()){
mockServer.shutdown()
}
}
abstract fun isMockServerEnabled(): Boolean
private fun setUpMockServer(){
if(isMockServerEnabled()){
mockServer = MockWebServer()
mockServer.start()
}
}
open fun mockHttpResponse(fileName: String, responseCode: Int) = mockServer.enqueue(MockResponse()
.setResponseCode(responseCode)
.setBody(getJson(fileName)))
private fun getJson(path : String) : String {
val uri = this.javaClass.classLoader!!.getResource(path)
val file = File(uri.path)
return String(file.readBytes())
}
private fun configureDI(){
//val coreComponent = DaggerCoreComponent.builder().contextModule(ContextModule(RuntimeEnvironment.application)).build()
DaggerTestHomeComponent.builder().build().inject(this)
}
}
The unit test class extends the base and sets up the viewModel by calling super.setUp() but this will always fail. Can anyone help me figure out how to make this work? I will be happy to provide more details if needed, am using robolectric 4.3
