加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

如何模拟Groovy中的Traits提供的方法/函数

发布时间:2020-12-14 16:27:34 所属栏目:大数据 来源:网络整理
导读:这是一个例子: trait Sender { def send(String msg){ // do something }}class Service implements Sender { def myMethod1(){ send('Foo') myMethod2() } def myMethod2(){ }} 我正在尝试测试Service类.但是,我想存根/模拟对特征(发送)提供的方法的调用?
这是一个例子:

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

class Service implements Sender {

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

    def myMethod2(){

    }
}

我正在尝试测试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

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

解决方法

尝试使用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' }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读