mockito Mockk:未找到部分匹配的模拟JPA调用的答案?

lokaqttq  于 2022-11-08  发布在  其他
关注(0)|答案(2)|浏览(134)

我正在尝试为一个更新API编写一个Junit测试用例。该API正在使用JPA的saveAll方法来执行更新。该API工作正常,但是当尝试模拟saveAll方法时,它会给我以下错误:
io.mockk.MockKException:未找到以下项的答案:用户资料档案库(#1).saveAll(用户详细信息..)

@Test
 fun testUpdateUserDetailsSuccess() {
   val userRepository = mockk<UserRepository>()

   every { userRepository.saveAll(anyList()) } returns getUserDetailsTestData();

   val userDetailsDatabaseAdapter = UserDetailsDatabaseAdapter(userRepository)
   val userResponse = userDetailsDatabaseAdapter.updateUserDetails(getUserDetails())
}

用户存储库

@Repository
interface UserRepository : JpaRepository<UserDetails, UUID> {
    fun findById(userId: UUID): List<UserDetails>
}

用户详细信息数据库适配器

override suspend fun updateUserDetails(userDetail: UserDetails): Either<CustomError, Int> =
            either {

//fetching some details from DB and then forming a list of userDetails

    val response = updateUserDetails(
                    userRepository,
                    userDetails
                ) andThen ::mapToCount
    response.bind()
    }

更新用户详细信息

fun updateUserDetails(
    userRepo: UserRepository,
    userDetails: List<UserDetails>
): Either<CustomError, List<UserDetails>> =
    bulkWriteToDatabase {
        userRepo.saveAll(userDetails)
    }

zc0qhyus

zc0qhyus1#

我看到你用的是Mockito标签,但你用的是Mockk。
那是不是anyList()的声音?
如果是这样的话,您就混合了MockitoMockk库。
相反,您是否可以尝试将Mockito的anyList()替换为Mockk的any()以进行部分匹配:

@Test
 fun testUpdateUserDetailsSuccess() {
   val userRepository = mockk<UserRepository>()

   every { userRepository.saveAll(any()) } returns getUserDetailsTestData();

   val userDetailsDatabaseAdapter = UserDetailsDatabaseAdapter(userRepository)
   val userResponse = userDetailsDatabaseAdapter.updateUserDetails(getUserDetails())
}

请参阅:Mockk -部分参数比对

44u64gxh

44u64gxh2#

我建议如下(注意any()getUserDetailsTestData()的赋值):

@Test
fun testUpdateUserDetailsSuccess() {
  val userRepository = mockk<UserRepository>()
  val userDetails = getUserDetailsTestData()

  every { userRepository.saveAll(any()) } returns userDetails

  val userDetailsDatabaseAdapter = UserDetailsDatabaseAdapter(userRepository)
  val userResponse = userDetailsDatabaseAdapter.updateUserDetails(getUserDetails())
}

相关问题