用Junit5和mockito测试错误处理方法的怪异

问题描述 投票:0回答:2

我正在为一个执行异常处理的方法进行单元测试。这是我想要测试的简化类:

class Foo{

    private BarService bar;

    public int MethodToTest(){

        try{
            bar.methodThatThrows();
            return 1;
        }catch(Exception e){
            return 0;
        }
    }
}

这是单元测试类。

class FooTest{

    private IBarService barService = mock(BarService.class);

    @Test
    TestMethodToTest(){

        when(barService.methodThatThrows()).thenThrow(new Exception("message");
        Foo foo = new foo();
        ReflectionTestUtils.setField(foo, "barService", barService);
        assertEquals(foo.MethodToTest(), 0);
    }
}

不知何故,当我运行它时,它会失败,因为抛出了一个错误(如预期的那样),它与我放入模拟服务的消息完全相同。当我在调试模式下运行时,catch块甚至都没有运行。这怎么可能?

java mockito junit5
2个回答
0
投票

很可能你在测试中抛出了一个未经methodThatThrows声明的检查异常

您在测试中声明的消息确实打印到控制台,但消息提供的信息更多:

org.mockito.exceptions.base.MockitoException: 
Checked exception is invalid for this method!
Invalid: java.lang.Exception: message

例如(在BarService中声明的IOException,但测试代码中抛出了更常见的已检查异常):

public class BarService {
    public int methodThatThrows() throws IOException {
        return 1;
    }
}

-1
投票

您没有在示例代码中正确设置BarService。你在做:

ReflectionTestUtils.setField(foo, "barService", barService);

但是在Foo类中,BarService变量被称为“bar”,而不是“barService”,所以你需要这样做:

ReflectionTestUtils.setField(foo, "bar", barService);

虽然“正确”的方法是使用Spring将BarService自动装配到Foo,这样可以避免首先使用ReflectionTestUtils

© www.soinside.com 2019 - 2024. All rights reserved.