Issue
I am completely new to Unit Testing in Android. I want to write the unit test for a method in my presenter class.
Sharing the methods need to be covered with unit test
override fun getRequiredUri(uri: Uri): Uri {
val moduleName = uri.moduleName
return when (moduleName) {
"sample" -> getStandardUriFromSampleUri(uri)
"application" -> getStandardAppLaunchUri(uri)
else -> {
return uri
}
}
}
private fun getStandardUriFromSampleUri(uri: Uri): Uri {
var stringUrl = uri.toString()
stringUrl = stringUrl.replaceFirst("/sample", "")
var standardUri = Uri.parse(stringUrl)
val moduleName = uri.moduleName
if(moduleName == "application"){
standardUri = getStandardAppLaunchUri(uri)
}
return standardUri
}
private fun getStandardAppLaunchUri(uri: Uri): Uri {
var stringUrl = uri.toString()
stringUrl = stringUrl.replaceFirst("application", "link/application")
return Uri.parse(stringUrl)
}
I am sharing my test class that I have tried to implement:
class PresenterTest {
lateinit var presenter: Presenter
@Mock
lateinit var mockActivity: Activity
@Mock
lateinit var mockUri: Uri
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
presenter = Presenter()
presenter.view = mockActivity
}
@Test
fun shouldGenerateStandardUriFromNewUri() {
val input = Uri.parse("https://example.org/sample/account/edit")
val expectedOutput = Uri.parse("https://example.org/account/edit")
val output = presenter. getRequiredUri(input)
assertTrue(output == expectedOutput)
}
}
This line is getting failed always with class not found an exception.
val output = presenter.getRequiredUri(input)
Is this the right way to unit test the method? If yes, please suggest the changes that I need to make. If no, then please suggest the alternative ways.
Solution
The crash is occurring at the line
uri.moduleName
ie: The path segments (uri.patheSegments) are empty while creating a Uri object from test class.
The solution is to run the Test Class with RoboElectricTestRunner.
That is the test class should look like this:
@Config(constants = BuildConfig::class)
@RunWith(RobolectricTestRunner::class)
class UriInterceptPresenterTest {
//-----Test cases-----
}
Answered By - Suneesh Ambatt
Answer Checked By - Katrina (JavaFixing Volunteer)