mockito更期待使用spy进行异常测试



如何进行第三次测试,以检查异常消息中是否存在cause1?我还列出了前两个测试中存在的缺点。首先是不检查消息,其次需要大量样板代码。

public class CheckExceptionsWithMockitoTest {
    @Test(expected = RuntimeException.class)
    public void testExpectedException1() {
        A a = new A();
        a.doSomethingThatThrows();
    }
    @Test
    public void testExpectedException2() {
        A a = new A();
        try {
            a.doSomethingThatThrows();
            fail("no exception thrown");
        } catch (RuntimeException e) {
            assertThat(e.getMessage(), org.hamcrest.Matchers.containsString("cause1"));
        }
    }
    @Test
    public void testExpectedException3() {
        A a = new A();
        A spyA = org.mockito.Mockito.spy(a);
        // valid but doesnt work
        // doThrow(new IllegalArgumentException()).when(spyA).doSomethingThatThrows();
        // invalid but in the spirit of what i want 
        //chekThrow(RuntimeException.class,containsString("cause1")).when(spyA).doSomethingThatThrows();
    }
}

我在Mockito中找不到有效的东西,但有一些东西看起来是可能的(在语法层面)和功能。


使用catchexception,我创建了这样的测试

import static com.googlecode.catchexception.CatchException.*;
import static com.googlecode.catchexception.apis.CatchExceptionHamcrestMatchers.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import org.junit.*;
public class CheckExceptionsWithMockitoTest{  
    //...
    @Test
    public void testExpectedException3() {
        A a = new A();
        verifyException(a,IllegalArgumentException.class)
            .doSomethingThatThrows();
        //if more details to be analized are needed
        assertThat(
            (IllegalStateException) caughtException(),
            allOf(
                is(IllegalStateException.class),
                hasMessageThat(
                        containsString("is not allowed to add counterparties")), 
                hasNoCause()));
        //more asserts could come
        assertNotNull(a);
    }
}

使用catch异常库,或者我猜您正在寻找的解决方案是您的第二个实现。

@expected除了它的类之外,没有提供任何方法来断言抛出的异常,所以你不能避免尝试/捕获(没有那么多锅炉板代码!)

Mockito没有提供类似于verifyThrows方法的东西。

因此,您可以用try/catching来换取一个额外的库:使用catch-exception,您将能够在一行中捕获异常,并为进一步的断言做好准备。

示例源代码

A a = new A();
when(a).doSomethingThatThrows();
then(caughtException())
        .isInstanceOf(IllegalStateException.class)
        .hasMessageContaining("is not allowed to add counterparties")
        .hasNoCause();

依赖项

'com.googlecode.catch-exception:catch-exception:1.2.0'

如果A是您正在测试的系统,那么嘲笑它没有任何意义,监视它也很少有意义。您在testExpectedException2中的实现是正确的;样板代码是必要的,因为如果没有CCD_。

虽然Mockito不会有任何帮助,但JUnit会的。@Test(expected=foo)参数实际上有一个更灵活的替代方案,即内置的ExpectedException JUnit规则:

public class CheckExceptionsWithMockitoTest {
  @Rule public ExpectedException thrown = ExpectedException.none();
  @Test
  public void testExpectedException1() {
    A a = new A();
    thrown.expect(RuntimeException.class);
    thrown.expectMessage(containsString("cause1"));
    a.doSomethingThatThrows();
  }
}

Mockito将在单独的测试中派上用场,检查您的方法是否包装了任意异常,同时保留其消息,大致如下:

@Test
public void doSomethingShouldWrapExceptionWithPassedMessage() {
  Dependency dependency = Mockito.mock(Dependency.class);
  when(dependency.call()).thenThrow(new IllegalArgumentException("quux"));
  A a = new A(dependency);
  thrown.expect(RuntimeException.class);
  thrown.expectMessage(containsString("quux"));
  a.doSomethingThatThrows();
}

要小心避免在测试中使这种模式成为常见模式的诱惑。如果您正在捕获从测试中的系统抛出的异常,那么您实际上是在将控制权交还给SUT的使用者。之后,除了异常的属性和可能的系统状态之外,方法中应该没有什么可测试的了,这两种情况都应该足够罕见,可以原谅try/catch样板。

如果您有机会使用scala,scalaTest的有趣套件有一种使用截距测试异常的简洁方法(http://www.scalatest.org/getting_started_with_fun_suite)。

它就像一样简单

  test(a list get method catches exceptions){
    intercept[IndexOutBoundsException]{
      spyListObject.get(-1)
    }
  }

如果您正在寻找易于编写/清除的测试,那么您可能会用scala将测试写入java项目。但这可能会带来其他挑战。

2015年6月19日更新答案(如果您使用的是java 8)

使用assertj-core-3.0.0+Java 8 Lambdas

@Test
public void shouldThrowIllegalArgumentExceptionWhenPassingBadArg() {
      assertThatThrownBy(() -> myService.sumTingWong("badArg"))
                                  .isInstanceOf(IllegalArgumentException.class);
}

参考:http://blog.codeleak.pl/2015/04/junit-testing-exceptions-with-java-8.html

我使用catchexception创建了类似的测试

import static com.googlecode.catchexception.CatchException.*;
import static com.googlecode.catchexception.apis.CatchExceptionHamcrestMatchers.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import org.junit.*;
public class CheckExceptionsWithMockitoTest{  
    //...
    @Test
    public void testExpectedException3() {
        A a = new A();
        verifyException(a,IllegalArgumentException.class)
            .doSomethingThatThrows();
        //if more details to be analized are needed
        assertThat(
            (IllegalStateException) caughtException(),
            allOf(
                is(IllegalStateException.class),
                hasMessageThat(
                        containsString("is not allowed to add counterparties")), 
                hasNoCause()));
        //more asserts could come
        assertNotNull(a);
    }
}

如果你在Mockito.class中查看了spy方法,它会使用spiedInstance:创建mock

 public static <T> T spy(T object) {
    return MOCKITO_CORE.mock((Class<T>) object.getClass(), withSettings()
            .spiedInstance(object)
            .defaultAnswer(CALLS_REAL_METHODS));
}

在MockSettings中,可以注册Invocation侦听器:https://static.javadoc.io/org.mockito/mockito-core/3.0.0/org/mockito/listeners/InvocationListener.html

我创建了一个简单的监听器,它存储所有报告的调用:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.mockito.listeners.InvocationListener;
import org.mockito.listeners.MethodInvocationReport;
public class StoringMethodInvocationListener implements InvocationListener {
private List<MethodInvocationReport> methodInvocationReports = new ArrayList<>();
@Override
public void reportInvocation(MethodInvocationReport methodInvocationReport) {
    this.methodInvocationReports.add(methodInvocationReport);
}
public List<MethodInvocationReport> getMethodInvocationReports() {
    return Collections.unmodifiableList(methodInvocationReports);
}

}

调用后,您可以查看报告,找到所需的报告,并验证存储的可丢弃文件是否为预期的报告。

示例:

    StoringMethodInvocationListener listener = new StoringMethodInvocationListener();
    Consumer mock2 = mock(Consumer.class, withSettings()
            .spiedInstance(consumerInstance)
            .defaultAnswer(CALLS_REAL_METHODS)
            .invocationListeners(listener));
    try {
        mock2.listen(new ConsumerRecord<String, String>(RECEIVER_TOPIC, 0, 0,  null, "{}"));
    } catch (Exception e){
        //nothing
    }
    Assert.notEmpty(listener.getMethodInvocationReports(), "MethodInvocationReports list must not be empty");
    Assert.isInstanceOf(BindException.class, listener.getMethodInvocationReports().get(1).getThrowable());

最新更新