[JUnit][莫吉托]如何验证方法是否在调用堆栈中调用了另一个级别



我有MyClass OtherClass作为字段:

public class MyClass
{
    @Autowired
    private OtherClass other;
    public void foo() {
        // Some interactions
        other.bar(someParameter);
    }
}
public class OtherClass
{
    public void bar() {
        // Some interactions
        if (someConditionThatIsTrue) {
            baz(someParam);
        }
    }
    public void baz(SomeParamClass param) {
        // Some interactions
    }
}

为了测试MyClass,我想检查OtherClass.baz()是否从MyClass.foo()调用。这是我所拥有的:

@RunWith(MockitoJUnitRunner.class)
public class MyClassTest {
    @InjectMocks
    private MyClass myClass;
    @Mock
    private OtherClass otherClass;
    @Test
    public void testFoo_whenFooIsCalled_shouldTriggerBaz() {
        // Some setups
        myClass.foo();
        verify(otherClass, times(1)).baz(any());
    }
}

上面的测试没有检测到OtherClass.baz(),但检测到OtherClass.bar()

Wanted but not invoked: otherClass.baz( <any> ); -> at MyClassTest.testFoo_whenFooIsCalled_shouldTriggerBaz(MyClassTest.java:12) However, there were other interactions with this mock: otherClass.bar( "some parameter" ); -> at MyClass.foo(MyClass.java:7)

在不重构MyClass的情况下,是否可以从测试中检测到OtherClass.baz()的实例?

你只需要使用间谍

@Spy
private OtherClass otherClass;

但是,这不是一个好的做法。您正在测试两个不同的类。我只是确保您使用正确的参数在第一次测试中调用bar。然后为 OtherClass 创建一个单独的单元测试文件。

最新更新