【问题标题】:Chaining side effects from spock stub with void return type使用 void 返回类型链接 spock 存根的副作用
【发布时间】:2015-07-24 10:57:36
【问题描述】:

我正在尝试测试以下(人为的)代码,它会进行调用,并在调用失败时尝试重试。

 public class MyObject
 {
    public void process(final Client client) throws IOException
    {
        try
        {
            client.send();
        }
        catch (IOException e)
        {
            client.fix();
        }

        try
        {
            client.send();
        }
        catch (IOException e)
        {
            throw new IOException(e);
        }
    }

    public class Client
    {
        public void send() throws IOException {}

        public void fix() {}
    }
}

我的测试策略是模拟 client 对象并存根响应,该响应将在第一次调用 send() 时引发异常,然后在第二次尝试时成功。

使用 spock,我有以下内容:

def "test method calls"() {
   setup:
   def MyObject myObject = new MyObject()
   def Client client = Mock(Client)

   when:
   myObject.process(client)

   then:
   2 * client.send() >>> {throw new IOException()} >> void
}

我已经尝试了上述方法,并将 void 替换为 null,并不断收到强制转换异常。

我也试过了:

2 * client.send() >>> [{throw new MyException()}, void]

如何模拟我想要的响应?

【问题讨论】:

  • client.send() >> { throw new MyException() } >> null
  • 我试过了,没用
  • 对我来说很好用,我设计它就是为了这样工作。也许您尝试了一些稍微不同的东西,例如使用 >>> 而不是 >> 在您的问题中,这是行不通的。
  • 我确认,Peter 的解决方案运行良好。

标签: java groovy spock


【解决方案1】:

此测试通过。我添加了 cmets 来显示每个步骤的含义:

def "test method calls"() {
    given:
    def MyObject myObject = new MyObject()
    def MyObject.Client client = Mock(MyObject.Client)
    //The first time client.send() is called, throw an exception
    1 * client.send() >> {throw new IOException()}
    //The second time client.send() is called, do nothing. With the above, also defines that client.send() should be called a total of 2 times. 
    1 * client.send()
    when:
    myObject.process(client)
    then:
    noExceptionThrown() //Verifies that no exceptions are thrown
    1 * client.fix() // Verifies that client.fix() is called only once.
}

【讨论】:

  • 完美,谢谢。我没有意识到两个独立的存根会像这样链接在一起。
  • @DanielScott 没问题。发现定义与 spock 的交互开始时非常棘手,但一旦你开始了解它,它就是一个很棒的单元测试工具。
【解决方案2】:

工作正常。

1*getName()>>"Hello"
1*getName()>>"Hello Java"

第一次调用我得到"Hello"。 第二次调用我得到"Hello Java"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-15
    • 1970-01-01
    • 2015-06-29
    • 2016-05-30
    • 2017-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多