I need to write test case for the switch condition in kotlin
.
Class.kt
fun getEnvSwitchURL(applicationContext: Context, envSwitchInfo: String): String {
val resources = applicationContext.getResources()
val assetManager = resources.getAssets()
val properties = Properties()
try {
val inputStream = assetManager.open("configuration.properties")
properties.load(inputStream)
val urlPref = applicationContext.getSharedPreferences(SELECTED_ENV, Context.MODE_PRIVATE)
val editor = urlPref.edit()
when (envSwitchInfo) {
"Production" ->{
editor.putString("selectedUrl", properties.getProperty("prodUrl"))
editor.apply()
selectedUrl=properties.getProperty("prodUrl")
}
"Development" ->{
editor.putString("selectedUrl", properties.getProperty("devUrl"))
editor.apply()
selectedUrl=properties.getProperty("devUrl")
}
"Testing" ->{
editor.putString("selectedUrl", properties.getProperty("testUrl"))
editor.apply()
selectedUrl=properties.getProperty("testUrl")
}
}
inputStream.close()
}
return selectedUrl
}
test.kt
@BeforeEach
fun runBeforeTest() {
testApplicationContext = Mockito.mock(Context::class.java)
testResource = Mockito.mock(Resources::class.java)
testAsset = Mockito.mock(AssetManager::class.java)
testInputStream = Mockito.mock(InputStream::class.java)
testSharedPref=Mockito.mock(SharedPreferences::class.java)
testEditor=Mockito.mock(SharedPreferences.Editor::class.java)
testProperties=Mockito.mock(Properties::class.java)
testProperties.setProperty("prodUrl", "Value");
}
Dhaval Shah
fun getEnvSwitchURL() {
Mockito.when
(testApplicationContext.getResources()).thenReturn(testResource)
Mockito.when
(testResource.assets).thenReturn(testAsset)
Mockito.when
(testAsset.open(Mockito.anyString())).thenReturn(testInputStream)
PowerMockito.whenNew(Properties::class.java).withNoArguments().thenReturn(testProperties)
Mockito.doNothing().when
(testProperties).load(Mockito.any(InputStream::class.java))
Mockito.when
(testApplicationContext.getSharedPreferences(anyString(),anyInt())).thenReturn(testSharedPref)
Mockito.when
(testSharedPref.edit()).thenReturn(testEditor)
envSwitchUtils.getEnvSwitchURL(testApplicationContext, testEnvSwitchInfo)
}
Above written test case is working fine. I need to find out how to write test case for switch condition for the above class. Kindly help me to write the same
I haven’t answered your question, but perhaps refactoring your code slightly makes it more obvious to test:
You could do a lot more here, look into the Single Responsibilty Principle. This is a start, for unit testing you don’t want to test that SharePreferences works correctly because then you are testing the platform and not your code. You may want to test only that when you pass an environment like “Production”, then the selectedUrl you get is returned.
Testing inputs and outputs as described above would be something like this:
and another test