我在对我的用例进行单元测试时遇到了问题。这是用例代码-
interface MyUseCase {
fun performCustomAction(action: MyAction): LiveData<Result>
}
class MyUseCaseImpl(private val dataRepository: DataRepository) : MyUseCase {
override fun performCustomAction(action: MyAction) = liveData {
emit(Result.DataFetchInProgress)
emit(dataRepository.performDataOperation(action))
}
}
这是对应的单元测试——
class MyUseCaseImplTest {
@Rule
@JvmField
val rule = InstantTaskExecutorRule()
private lateinit var myUseCase: MyUseCase
@Mock
private lateinit var dataRepository: DataRepository
@Mock
private lateinit var liveData: LiveData<Result>
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
myUseCase = spy(MyUseCaseImpl(dataRepository))
}
@After
fun tearDown() {
}
@Test
fun myUseCase_loginUser_expectedUserLoggedIn() {
val result: LiveData<Result> = myUseCase.performCustomAction(
MyAction.LoginUser(
"userName", "password"
)
)
Assert.assertEquals(result, liveData)
}
}
当我运行这个单元测试时,我收到此错误 -
java.lang.AssertionError:
Expected :androidx.lifecycle.CoroutineLiveData@4c012563
Actual :liveData
我在这里犯了什么错误?
另外,您能否建议我还可以在我的用例中测试什么
我修复了它。基本上我需要添加一个Mockito.when(...).thenReturn(livedata)
. 这是下面的代码 -
@Test
fun myUseCase_loginUser_expectedUserLoggedIn() {
`when`(
myUseCase.performCustomAction(
MyAction.LoginUser(
"userName", "password"
)
)
).thenReturn(liveData)
val result = myUseCase.performCustomAction(
MyAction.LoginUser(
"userName", "password"
)
)
Assert.assertThat(result, `is`(liveData))
}