【问题标题】:JMockit multiple exceptions as result for method callJMockit 多个异常作为方法调用的结果
【发布时间】:2012-12-28 09:24:47
【问题描述】:

这是来自官方的 JMockit 教程:

@Test
   public void doSomethingHandlesSomeCheckedException() throws Exception
   {
      new Expectations() {
         DependencyAbc abc;

         {
            abc.stringReturningMethod();
            returns("str1", "str2");
            result = new SomeCheckedException();
         }
      };

      new UnitUnderTest().doSomething();
   }

是否可以反过来说,即多个结果和一个返回 - 我需要抛出 2 个异常,然后才返回一个好的值。我正在寻找这样的东西:

  abc.stringReturningMethod();
  returns(new SomeCheckedException(), new SomeOtherException(),"third");

这不起作用,JMockit 无法将这些异常转换为 String(这是 stringReturningMethod 的返回类型)

【问题讨论】:

    标签: java unit-testing junit jmockit


    【解决方案1】:

    这样写:

        abc.stringReturningMethod();
        result = new SomeCheckedException();
        result = new SomeOtherException();
        result = "third";
    

    【讨论】:

    • 不会将所有三个调用的结果都设置为third吗?
    • 不。它将记录stringReturningMethod() 的三个连续结果。 (“结果”要么是要返回的值、要抛出的异常,要么是要执行的 Delegate。JMockit 会自动将这些分配重写为对其内部方法的调用,这就是它起作用的原因。)
    • 这不起作用。你必须做result = new SomeCheckedException(); result = new SomeOtherException(); returns("Non-exception-String-value");
    【解决方案2】:

    我不知道是否有捷径可以做到这一点,但您总是可以记录该方法将被多次调用:

    abc.stringReturningMethod();
    result = new SomeCheckedException();
    
    abc.stringReturningMethod();
    result = new SomeOtherException();
    
    abc.stringReturningMethod();
    result = "third";
    

    【讨论】:

    • 我觉得这对我不起作用我试过了,我试过 abc.getCode() result = 1;然后 abc.getCode() result = new RuntimeException() 并且它不能正常工作......但是,另一个答案有效。
    猜你喜欢
    • 1970-01-01
    • 2013-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-01
    • 1970-01-01
    相关资源
    最近更新 更多