Reputation: 680
I have battled with this for several days. This mock will not return SUCCESS
(true): 1 * realtimeClient.send(_) >> SUCCESS
.
From question 41841668 I found I needed the 1 *
, which I added without success. I am printing out an intermediate variable of the result of realtimeClient.send()
and it is always false.
RealtimeClient
and QueueClient
are interfaces. I tried coding the RestfulEmailController
and the Spock test with concrete classes, no change in behavior. I've tried big Boolean
instead of little boolean
, no change. The documentation says this should work, and question 41841668 says this should work (although with less complete example code).
public static final boolean SUCCESS = true
def "test real time email success"() {
given:
RealtimeClient realtimeClient = Mock()
QueueClient queueClient = Mock()
1 * realtimeClient.send(_) >> SUCCESS
RestfulEmailController restfulEmail = new RestfulEmailController(realtimeClient: realtimeClient, queueClient: queueClient)
RestfulEmailContract email = new RestfulEmail(subject: "some subject")
when:
restfulEmail.sendRestfulEmail(email)
then:
1 * realtimeClient.send(_)
0 * queueClient.send(_)
}
and the controller class stripped down to a basic example looks like
void sendRestfulEmail(@RequestBody RestfulEmail emailRequest) {
boolean success = realtimeClient.send(emailRequest)
System.out.println("success = " + success )
if (!success ) {
queueClient.send(emailRequest)
}
}
nothing I do can make the system print "success = true", and I fail on the expectation for 0 * queueCient.send(_)
Upvotes: 0
Views: 290
Reputation: 13242
See Combining Mocking and Stubbing in the docs, if you mock something and need to return a value, you must do it at the same time. So if you merge the line 1 * realtimeClient.send(_) >> SUCCESS
from the given
block into the then
block, then it returns the value as you'd expect.
def "test real time email success"() {
given:
RealtimeClient realtimeClient = Mock()
QueueClient queueClient = Mock()
RestfulEmailController restfulEmail = new RestfulEmailController(realtimeClient: realtimeClient, queueClient: queueClient)
RestfulEmailContract email = new RestfulEmail(subject: "some subject")
when:
restfulEmail.sendRestfulEmail(email)
then:
1 * realtimeClient.send(_) >> SUCCESS
0 * queueClient.send(_)
}
Upvotes: 2