我正在创建一个简单的 junit 测试来测试我的视图模型中的函数,但第一个断言失败,因为我调用的函数返回 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"))
}
}
模拟类不会真正被调用。如果要测试currencyViewModel.calculateValue((方法,请创建该类的真实对象并模拟可能的构造函数参数。
补充一下 Ben 所说的话:你想要测试的类必须是真实的对象,而不是模拟对象。默认情况下,模拟"什么都不做",只做你告诉你的事情,所以测试它没有任何意义。
你模拟的是你测试的类的依赖关系,即你传递给它的构造函数的对象。
简而言之:如果你想测试CurrencyViewModel
,创建一个对象而不是嘲笑它。