我想模拟我的服务类并调用它从抽象类和接口继承的任何方法,就像它们属于服务一样。不幸的是,当我模拟服务并从抽象类调用方法时,mockito 会调用抽象类中的真实方法。是否有可能以某种方式完全模拟服务类?
界面:
interface MessageProducer<T> {
fun sendMessage(data: T)
}
抽象类:
abstract class AuditableMessage<T>(
private val auditService: AuditService
) : MessageProducer<T> {
protected abstract val auditPoint: String
fun sendAuditJsonMessage(data: T) {
auditService.auditJson(auditPoint, data as Any)
sendMessage(data)
}
)
混凝土弹簧服务
@Service
class ClientProducer(
private val kafkaProducer: KafkaTemplate<String, String>,
auditService: AuditService
) : AuditableMessage<String>(auditService) {
override val auditPoint: String = "MY_AUDIT_POINT"
override fun sendMessage(data: String) {
kafkaProducer.sendDefault(data)
}
}
测试班
@ExtendWith(MockitoExtension::class)
internal class ClientRequestServiceTest {
@Mock
lateinit var clientProducer: clientProducer
@InjectMocks
lateinit var clientRequestService: ClientRequestService
@Captor
lateinit var requestCaptor: ArgumentCaptor<String>
@Test
fun `test createClient creates request and calls send message`() {
...
clientRequestService.createClient(clientData)
verify(clientProducer).sendAvroAuditJsonMessage(capture(requestCaptor))
}
}
更新测试用例: 我有一个注入 ClientProducer 并调用其方法的默认服务。
@Service
class ClientRequestService(
private val primeClientProducer: clientProducer
) {
fun createClient(clientData: PrimeAddClientInput) {
try {
clientProducer.sendAvroAuditJsonMessage("TEST")
} catch (e: Exception) {
log.error {""}
throw e
}
}
@ExtendWith(MockitoExtension::class)
internal class ClientRequestServiceTest {
@Mock
lateinit var primeClientProducer: PrimeClientProducer
@InjectMocks
lateinit var clientRequestService: ClientRequestService
@Captor
lateinit var requestCaptor: ArgumentCaptor<String>
@Test
fun `test createClient creates request and calls send message`() {
val clientData = easyRandom.nextObject(String::class.java)
clientRequestService.createClient(clientData)
verify(primeClientProducer).sendAvroAuditJsonMessage(capture(requestCaptor))
val request = requestCaptor.value
verify("TEST", request)
}
}
Exception:
java.lang.NullPointerException
at code.AuditService.auditJson$default(AuditService.kt:41)
at code.AuditableMessage.sendAvroAuditJsonMessage(AuditableMessage.kt:23)
at code.ClientRequestService.createClient(ClientRequestService.kt:20)
所以它基本上调用 auditService.auditJson(...) 但它不应该