如何模拟Groovy中的Traits提供的方法/功能

byt*_*ast 6 java groovy unit-testing mocking

这是一个例子:

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

class Service implements Sender {

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

    def myMethod2(){

    }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试测试Service类.但是,我想存根/模拟对特征(发送)提供的方法的调用?

我已经尝试了几种不同的方法来存根/模拟方法发送,但没有成功:

// 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
Run Code Online (Sandbox Code Playgroud)

这些只是我尝试过的一些事情.我甚至尝试使用像Mockito这样的模拟框架.不幸的是,似乎没有任何效果.有什么建议???

raf*_*lim 1

尝试使用Spock 框架中的Spy !

像这样:

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' }
    }
}
Run Code Online (Sandbox Code Playgroud)