Java JMockit方法调用的结果是多个异常
这来自官方的JMockit教程:Java JMockit方法调用的结果是多个异常,java,unit-testing,junit,jmockit,Java,Unit Testing,Junit,Jmockit,这来自官方的JMockit教程: @Test public void doSomethingHandlesSomeCheckedException() throws Exception { new Expectations() { DependencyAbc abc; { abc.stringReturningMethod(); returns("str1", "str2");
@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
的返回类型)我不知道是否有快捷方式可以这样做,但您可以随时记录该方法将被调用多次:
abc.stringReturningMethod();
result = new SomeCheckedException();
abc.stringReturningMethod();
result = new SomeOtherException();
abc.stringReturningMethod();
result = "third";
这样写:
abc.stringReturningMethod();
result = new SomeCheckedException();
result = new SomeOtherException();
result = "third";
它不会将所有三个调用的结果都设置为第三个吗?不会。它将记录
stringReturningMethod()
的三个连续结果。(一个“result”要么是一个要返回的值,要么是一个要抛出的异常,要么是一个要执行的委托。。JMockit会自动将这些赋值重写为对其内部方法的调用,这就是它工作的原因。)这不起作用。您必须执行result=newsomeCheckedException();结果=新的SomeOtherException();返回(“非异常字符串值”)代码>我觉得这对我不起作用我试过了,我试过了abc.getCode()结果=1;然后abc.getCode()result=new RuntimeException(),它无法正常工作。。。然而,另一个答案奏效了。