【发布时间】:2021-03-10 13:21:22
【问题描述】:
如果提供了null 值,我正在尝试测试一个将调用另一个Web 服务来获取数据的类。我的 JUnit + Mockito 测试效果很好,但我的 Spock 测试无法匹配 then: 块。 Spock测试时返回的错误是:
Suppressed: java.lang.NullPointerException: Cannot invoke method map() on null object
这是因为我的模拟方法不匹配,因此返回null。
Spock 测试(无效)
class MySpec extends Specfication {
def mockCollaboratingService = Mock(CollaboratingService)
def service = new MyService(collaboratingService: mockCollaboratingService)
def "should call another service if the provided start value equals null"() {
given:
def id = 123
def startDate = null
when: "the service is called"
def result = service.getTransactions(id, startDate)
then:
1 * mockCollaboratingService.getData(id) >> Mono.just(new SomeMockResponse(key: "123"))
StepVerifier
.create(result)
.consumeNextWith({
// assertions here
})
.verifyComplete()
}
}
JUnit + Mockito(工作)
class AnotherSpec {
def mockCollaboratingService = Mockito.mock(MockCollaboratingService)
def service = new MyService(collaboratingService: mockCollaboratingService)
@Test
@DisplayName("should call the statement service if the given start date is null")
void shouldCallStatementServiceIfStartDateEqualsNull() {
def id = 123
def startDate = null
// and some fake data returned from the api
Mockito.when(mockCollaboratingService.getData(id)).thenReturn(Mono.just(new SomeMockResponse(key: "123")))
//when
def result = service.getTransactions(id, null)
//then
StepVerifier
.create(result)
.consumeNextWith({
Mockito.verify(mockStatementService, Mockito.times(1)).getLastStatement(enterpriseToken)
assert it.transactionId == 123
})
.verifyComplete()
}
}
【问题讨论】:
标签: groovy junit mockito project-reactor spock