测试扩展抽象类和接口的Spring Service类



我想模拟我的服务类,并调用它从抽象类和接口继承的任何方法,就像它们属于服务一样。不幸的是,当我模拟服务并从抽象类调用方法时,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)
}
)

Concrete春季服务

@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(…(,但不应该调用

我在依赖关系中出现了一些不匹配。现在它工作正常

相关内容

  • 没有找到相关文章

最新更新