我能够调整我的测试,但失败了。问题是,模拟方法仍返回错误数据。这是我要测试的方法:
jQuery.noConflict();
jQuery('#myModal').modal('show');
}
这就是我测试方法的方式:
fun getTextByLanguage(list: List<TitleModel>) : String {
val deviceLanguage = Locale.getDefault().language
var default = ""
for (item in list) {
if (item.culture.contains(deviceLanguage, true)) return item.value
if (item.culture.contains("en", true)) default = item.value
}
return default
第一个测试用例没有问题,但第二个失败。这是输出:
import junit.framework.TestCase.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.powermock.api.mockito.PowerMockito.*
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
import java.util.Locale
@RunWith(PowerMockRunner::class)
@PrepareForTest(Locale::class)
class AppConfigUtilityByPowerMockTest {
@Test
fun `getTextByLanguage, test en`() {
mockStatic(Locale::class.java)
val mockedLocal = mock(Locale::class.java)
`when`(Locale.getDefault()).thenReturn(mockedLocal)
`when`(mockedLocal.language).thenReturn("en")
val list = listOf(TitleModel("en-ca", "Home"), TitleModel("fr-ca", "HomeFr"))
val actual = getTextByLanguage(list)
assertEquals("Home", actual)
}
@Test
fun `getTextByLanguage, test fr`() {
mockStatic(Locale::class.java)
val mockedLocal = mock(Locale::class.java)
`when`(Locale.getDefault()).thenReturn(mockedLocal)
`when`(mockedLocal.language).thenReturn("fr")
val list = listOf(TitleModel("en-ca", "Home"), TitleModel("fr-ca", "HomeFr"))
val actual = getTextByLanguage(list)
assertEquals("HomeFr", actual)
}
}
答案 0 :(得分:0)
回答问题的一种方法是从方法中摆脱Local
类,然后以Kotlin方式进行操作。所以,我要做的就是像这样更改我的原始方法:
fun getTextByLanguage(list: List<TitleModel>, deviceLanguage: String = getDeviceLanguage()) : String {
var default = ""
for (item in list) {
if (item.culture.contains(deviceLanguage, true)) return item.value
if (item.culture.contains("en", true)) default = item.value
}
return default
}
fun getDeviceLanguage(): String {
return Locale.getDefault().language
}
现在我的测试类如下:
import junit.framework.TestCase.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
import java.util.Locale
@RunWith(PowerMockRunner::class)
@PrepareForTest(Locale::class)
class AppConfigUtilityByPowerMockTest {
@Test
fun `getTextByLanguage, test en`() {
val list = listOf(TitleModel("en-ca", "Home"), TitleModel("fr-ca", "HomeFr"))
val actual = getTextByLanguage(list, "en")
assertEquals("Home", actual)
}
@Test
fun `getTextByLanguage, test fr`() {
val list = listOf(TitleModel("en-ca", "Home"), TitleModel("fr-ca", "HomeFr"))
val actual = getTextByLanguage(list, "fr")
assertEquals("HomeFr", actual)
}
}
尽管我的考试通过了,但我仍然愿意看到您的推荐,并接受您对我问题的回答。