Grails / Spock: How to mock single method within class where method is called from within the class itself?
Asked Answered
N

4

14

Given the following, how do I mock processMessage() using Spock, so that I can check that processBulkMessage() calls processMessage() n times, where n is the number of messages within a BulkMessage?

class BulkMessage {
    List messages
}

class MyService {

    def processBulkMessage(BulkMessage msg) {
        msg.messages.each {subMsg->
            processMessage(subMsg)
        }
    }

    def processMessage(Message message) {

    }
}
Namnama answered 12/12, 2014 at 14:47 Comment(0)
J
10

You can use spies and partial mocks (requires Spock 0.7 or newer).

After creating a spy, you can listen in on the conversation between the caller and the real object underlying the spy:

def subscriber = Spy(SubscriberImpl, constructorArgs: ["Fred"])
subscriber.receive(_) >> "ok"

Sometimes, it is desirable to both execute some code and delegate to the real method:

subscriber.receive(_) >> { String message -> callRealMethod(); message.size() > 3 ? "ok" : "fail" }
Jiggered answered 12/12, 2014 at 15:28 Comment(0)
E
2

In my opinion this is not a well designed solution. Tests and design walk hand in hand - I recommend this talk to investigate it better. If there's a need to check if other method was invoked on an object being under test it seems it should be moved to other object with different responsibility.

Here's how I would do it. I know how visibility works in groovy so mind the comments.

@Grab('org.spockframework:spock-core:0.7-groovy-2.0')
@Grab('cglib:cglib-nodep:3.1')

import spock.lang.*

class MessageServiceSpec extends Specification {

    def 'test'() {
        given:
        def service = new MessageService()
        def sender = GroovyMock(MessageSender)

        and:
        service.sender = sender

        when:
        service.sendMessages(['1','2','3'])

        then:
        3 * sender.sendMessage(_)
    }
}
class MessageSender { //package access - low level   
   def sendMessage(String message) {
      //whatever
   }
}

class MessageService {

   MessageSender sender //package access - low level

   def sendMessages(Iterable<String> messages) {
      messages.each { m -> sender.sendMessage(m) }
   }
}
Emmott answered 12/12, 2014 at 16:45 Comment(1)
Thanks very much - I've just revisited this and have learnt a lot about design since I asked the question. I now agree with you that the better design would be a bulkMessageProcessingService and an individualMessageProcessingService. Testing is therefore trivial with a mock.Namnama
F
1

It does not use Spock built-in Mocking API (not sure how to partially mock an object), but this should do the trick:

class FooSpec extends Specification {

    void "Test message processing"() {
        given: "A Bulk Message"
        BulkMessage bulk = new BulkMessage(messages: ['a', 'b', 'c'])

        when: "Service is called"
        def processMessageCount = 0
        MyService.metaClass.processMessage { message -> processMessageCount++ }
        def service = new MyService()
        service.processBulkMessage(bulk)

        then: "Each message is processed separately"
        processMessageCount == bulk.messages.size()
    }
}
Flaggy answered 12/12, 2014 at 15:22 Comment(0)
R
1

For Java Spring folks testing in Spock:

constructorArgs is the way to go, but use constructor injection. Spy() will not let you set autowired fields directly.

// **Java Spring**
class A {
    private ARepository aRepository;

    @Autowire
    public A(aRepository aRepository){
        this.aRepository = aRepository;
    }

    public String getOne(String id) {
        tryStubMe(id)  // STUBBED. WILL RETURN "XXX"
        ...
    }

    public String tryStubMe(String id) {
        return aRepository.findOne(id)
    }

    public void tryStubVoid(String id) {
        aRepository.findOne(id)
    }
}

// **Groovy Spock**
class ATest extends Specification {

    def 'lets stub that sucker' {
        setup:
            ARepository aRepository = Mock()
            A a = Spy(A, constructorArgs: [aRepository])
        when:
            a.getOne()
        then:
            // Stub tryStubMe() on a spy
            // Make it return "XXX"
            // Verify it was called once
            1 * a.tryStubMe("1") >> "XXX"
    }
}      

Spock - stubbing void method on Spy object

// **Groovy Spock**
class ATest extends Specification {

    def 'lets stub that sucker' {
        setup:
            ARepository aRepository = Mock()
            A a = Spy(A, constructorArgs: [aRepository]) {
                1 * tryStubVoid(_) >> {}
            }
        when:
            ...
        then:
            ...
    }
} 
Retene answered 2/2, 2016 at 16:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.