嗨,我有一个名为UserServiceTest的测试类,其中包含与上述模拟一起注入的userService类,并且该测试类中的测试正常运行。
@RunWith(MockitoJUnitRunner::class)
class UserServiceTest {
lateinit var login: Login
@Mock
lateinit var userRepository: UserRepository
@Mock
lateinit var emailService: EmailService
@InjectMocks
lateinit var userService: UserService
@Before
fun setup() {
login = Login(email = "mohanraj@gmail.com", password = "qwerty"
}
我还有另一个名为AdminServiceTests的测试类,其中包含AdminServiceClass,该类与上述模拟一起注入,其中也包含userService类
@RunWith(MockitoJUnitRunner::class)
class AdminServiceTests {
lateinit var user: User
@Mock
lateinit var userRepository: UserRepository
@Mock
lateinit var adminRepository: AdminRepository
@Mock
lateinit var userService: UserService
@InjectMocks
lateinit var adminService: AdminService
@Before
fun setup() {
this.createAdmin = CreateAdmin().apply {
email = "admin@gmail.com"
name = "admin"
password = "qwerty"
phone = 98345678899
}
}
@Test
fun testCreateAdmin() {
val result = adminService.createAdmin(createAdmin)
Assert.assertEquals(true, result)
}
运行测试时,adminService.createAdmin(createAdmin)在adminService中调用一个函数,在adminService中调用一个函数
fun createAdmin(newUser: CreateAdmin): Boolean {
val user = userService.getUser(newUser)
if (userService.createUser(user)) { // calls a function in user service
this.saveAdmin(user.id)
return true
}
return false
}
我想从testCreateAdmin函数中调用userService中的一个函数,但是我作为@Mock包含的用户服务本身包含一些依赖关系,并且它是adminService的依赖关系,因此当我调试@Mock userService对象时,其包含null因此,不会调用userService中的函数。那么如何将依赖项注入到userService并将其注入到adminService中。请帮助
userService = {UserService$MockitoMock$825690330@2479}
mockitoInterceptor = {MockMethodInterceptor@2532}
userRepository = null
emailService = null
答案 0 :(得分:1)
在您的testCreateAdmin()
中,您必须模拟userService
方法的行为。默认情况下,非模拟方法将返回null
。
它应该是这样的,带有mockito-kotlin。
@Test
fun testCreateAdmin() {
val admin = mock<User>() {
on { id } doReturn "id"
}
whenever(userService.getUser(createAdmin)).doReturn(admin)
whenever(userService.createUser(admin)).doReturn(true)
val result = adminService.createAdmin(createAdmin)
Assert.assertEquals(true, result)
verify(userService).saveAdmin("id")
}