安卓存储库单元测试



我的存储库单元测试遇到问题,没有得到预期的结果。谁能指出我的问题。

在测试中,从存储库中读出给了我一个意想不到的值。

这是我的存储库代码 -

interface DataRepository {
suspend fun changeCustomDataBasedOnAction(action: MyAction): Result
}
class DataRepositoryImpl(
private val cacheRepository: CacheRepository
) : DataRepository {
override suspend fun changeCustomDataBasedOnAction(action: MyAction): Result {
when (action) {
is MyAction.StoreUser -> {
print("Storing to cache" + action.userName + action.userAge)
cacheRepository.storeUserDetails(
UserModel(
action.userName,
action.userAge
)
)
return isUserDetailsStored()
}
}
}
private suspend fun isUserDetailsStored(): Result {
val result = cacheRepository.retrieveUserDetails()
print("Reading from cache" + result)
if (result is Result.GetUserDetails) {
return Result.UserDetailsStored
}
return Result.UserDetailsNotStored
}
}

这是我对应的单元测试——

class DataRepositoryImplTest {
@get:Rule
val instantExecutorRule = InstantTaskExecutorRule()
private lateinit var dataRepository: DataRepository
@Mock
private lateinit var cacheRepository: CacheRepository
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
dataRepository = DataRepositoryImpl(cacheRepository)
}
@After
fun tearDown() {
}
@Test
fun data_storeUser_returnUserDetailsStored() {
runBlocking {
`when`(
dataRepository.changeCustomDataBasedOnAction(
MyAction.StoreUser(
"username", "40"
)
)
).thenReturn(Result.UserDetailsStored)
val result = dataRepository.changeCustomDataBasedOnAction(
MyAction.StoreUser(
"username", "40"
)
)
Assert.assertEquals(result, Result.UserDetailsStored)
}
}
}

问题是我得到了这个测试结果——

Storing to cache username40
Reading from cache null
Storing to cache username40
Reading from cache com.user.app.Result$UserDetailsStored@2584b82d
java.lang.AssertionError: 
Expected :com.user.app.Result$UserDetailsNotStored@7bbc8656
Actual   :com.user.app.Result$UserDetailsStored@2584b82d

首先,你做 UnitTest 不正确。UT 类 DataRepositoryImpl 不负责检查用户是否已成功存储。如果是这样,则需要提供 cacheRepository 的真实实例。 其次,你可以写两个单元测试用例正负,如下所示

@Test
fun data_storeUser_returnUserDetailsStored() {
runBlocking {
`when`(cacheRepository.retrieveUserDetails())
).thenReturn(Result.GetUserDetails)
val result = dataRepository.changeCustomDataBasedOnAction(
MyAction.StoreUser(
"username", "40"
)
)
Assert.assertEquals(result, ListenableWorker.Result.UserDetailsStored)
}
}
@Test
fun data_storeUser_returnUserDetailsNotStored() {
runBlocking {
`when`(cacheRepository.retrieveUserDetails())
).thenReturn(Result.UserDetailsNotStored)
val result = dataRepository.changeCustomDataBasedOnAction(
MyAction.StoreUser(
"username", "40"
)
)
Assert.assertEquals(result, ListenableWorker.Result.UserDetailsNotStored)
}
}

用于检查数据实际缓存的单元测试用例可以单独写入 cacheRepository 测试类中。

相关内容

  • 没有找到相关文章

最新更新