Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock methods/functions provided by Traits in Groovy

Here's an example:

trait Sender {
    def send(String msg){
        // do something
    }
}

class Service implements Sender {

    def myMethod1(){
        send('Foo')
        myMethod2()
    }

    def myMethod2(){

    }
}

I am trying to test the Service class. However, I would like to stub/mock the calls to the methods provided by the trait (send)?

I have tried several different ways to stub/mock the method send, with no success:

// 1
Service.metaclass.send = { String s -> // do nothing }

// 2
def service = new MyService()
service.metaClass.send = { String s -> // do nothing }

// 3
StubFor serviceStub = new StubFor(Service.class)
serviceStub.demand.send { String s -> // do nothing }

// 
trait MockedSender {
  def send(String msg) { // do nothing }  
}
def service = new Service() as MockedSender

These are just some of the things I tried. I even tried using Mock frameworks like Mockito. Unfortunately, nothing seems to work. Any suggestions???

like image 836
bytekast Avatar asked Apr 21 '16 04:04

bytekast


1 Answers

Try using Spy from Spock framework!

Like this:

trait Sender {
    def send(String msg){
        println msg
    }
}

class Service implements Sender {

    def myMethod1(){
        send('Foo')
        myMethod2()
    }

    def myMethod2(){
        println 'real implementation'
    }
}

class UnitTest extends Specification {

    def "Testing spy on real object"() {
        given:
        Service service = Spy(Service)
        when:
        service.myMethod1()
        then: "service.send('Foo') should be called once and should print 'mocked' and 'real implementation' on console"
        1 * service.send('Foo') >> { println 'mocked' }
    }
}
like image 153
rafaelim Avatar answered Oct 23 '22 17:10

rafaelim