JUnit 测试不将值作为参数发送到函数 (Kotlin)
JUnit test not sending values as parameters to function (Kotlin)
我正在创建一个简单的 junit 测试来测试我的视图模型中的函数,但第一个断言失败,因为我调用的函数为 returns null。当我调试我调用的函数时有空参数,这很奇怪,因为我传入了它们。
我已经花时间调试和搜索我遇到这个问题的原因,但我没有找到任何可以解决我的问题或告诉我问题是什么的东西。
@RunWith(MockitoJUnitRunner::class)
class CurrencyUnitTest {
@Rule
@JvmField
val rule = InstantTaskExecutorRule()
@Mock
val currencyViewModel : CurrencyViewModel = mock(CurrencyViewModel::class.java)
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
val rates: HashMap<String, Double> =
hashMapOf(
"USD" to 1.323234,
"GBP" to 2.392394,
"AUD" to 0.328429,
"KWR" to 893.4833
)
val currencyRates = MutableLiveData<Resource<CurrencyRatesData?>>()
val resource = Resource<CurrencyRatesData?>(Status.SUCCESS, CurrencyRatesData("CAD", rates, 0))
currencyRates.value = resource
`when`(currencyViewModel.currencyRatesData).thenReturn(currencyRates)
val baseCurrency = MutableLiveData<String>()
baseCurrency.value = "CAD"
`when`(currencyViewModel.baseCurrency).thenReturn(baseCurrency)
}
@Test
fun calculateValueTest() {
// this fails
assertEquals("0.36", currencyViewModel.calculateValue("AUD", "1.11"))
}
}
模拟的 classes 不会真正被调用。如果您想测试 currencyViewModel.calculateValue() 方法,请创建该 class 的真实对象并模拟可能的构造函数参数。
补充一下 Ben 所说的:您要测试的 class 必须是真实对象,而不是模拟对象。默认情况下是一个模拟 "does nothing",它只会告诉你你所做的,所以测试它没有任何意义。
您模拟的是您测试的 class 的依赖项,即您传递给其构造函数的对象。
简而言之:如果您想测试 CurrencyViewModel
,请创建它的对象而不是模拟它。
我正在创建一个简单的 junit 测试来测试我的视图模型中的函数,但第一个断言失败,因为我调用的函数为 returns null。当我调试我调用的函数时有空参数,这很奇怪,因为我传入了它们。
我已经花时间调试和搜索我遇到这个问题的原因,但我没有找到任何可以解决我的问题或告诉我问题是什么的东西。
@RunWith(MockitoJUnitRunner::class)
class CurrencyUnitTest {
@Rule
@JvmField
val rule = InstantTaskExecutorRule()
@Mock
val currencyViewModel : CurrencyViewModel = mock(CurrencyViewModel::class.java)
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
val rates: HashMap<String, Double> =
hashMapOf(
"USD" to 1.323234,
"GBP" to 2.392394,
"AUD" to 0.328429,
"KWR" to 893.4833
)
val currencyRates = MutableLiveData<Resource<CurrencyRatesData?>>()
val resource = Resource<CurrencyRatesData?>(Status.SUCCESS, CurrencyRatesData("CAD", rates, 0))
currencyRates.value = resource
`when`(currencyViewModel.currencyRatesData).thenReturn(currencyRates)
val baseCurrency = MutableLiveData<String>()
baseCurrency.value = "CAD"
`when`(currencyViewModel.baseCurrency).thenReturn(baseCurrency)
}
@Test
fun calculateValueTest() {
// this fails
assertEquals("0.36", currencyViewModel.calculateValue("AUD", "1.11"))
}
}
模拟的 classes 不会真正被调用。如果您想测试 currencyViewModel.calculateValue() 方法,请创建该 class 的真实对象并模拟可能的构造函数参数。
补充一下 Ben 所说的:您要测试的 class 必须是真实对象,而不是模拟对象。默认情况下是一个模拟 "does nothing",它只会告诉你你所做的,所以测试它没有任何意义。
您模拟的是您测试的 class 的依赖项,即您传递给其构造函数的对象。
简而言之:如果您想测试 CurrencyViewModel
,请创建它的对象而不是模拟它。