简体   繁体   English

是否可以使用Mockito验证测试的对象方法调用?

[英]Is it possible to verify tested object method call with Mockito?

I' ve got some business logic class: 我有一些业务逻辑课:

public class SomeService {
    public void doFirst() {}

    public void doSecond() {
        doFirst();
    }
}

and test for it: 并测试:

public class SomeServiceTest {

    private SomeService service;

    @Before
    public void setUp() {
        service = new SomeService();
    }

    @Test
    public void doSecond_someCondition_shouldCallFirst() {

        // given
        ...

        // when
        service.doSecond();

        //then
        how to verify doFirst() was called? 
    }
}

How to verify doFirst() was called not on mock, but real service? 如何验证doFirst()不是在模拟中调用,而是在真实服务中调用?

I wonder why you want to test, what method your method under tests invoke. 我想知道为什么要测试,被测方法调用什么方法。 Sounds pretty much like whitebox testing to me. 听起来很像白盒测试。

In my opinion, you want to verify the outcome of the invocation and not the way to get there, as this might easily change (ie when refactoring). 在我看来,您想验证调用的结果而不是验证到达结果的方法,因为这很容易改变(即在重构时)。

So if the outcome of doSecond() is the same as doFirst() you could write a test for doFirst() and use the same test (ie set of assertions) for testing doSecond(). 因此,如果doSecond()的结果与doFirst()相同,则可以为doFirst()编写一个测试,并使用相同的测试(即一组断言)来测试doSecond()。

But if you really want to test, whether doFirst() has been invoked by doSecond() you could wrap your service in a spy and then call the verification on the spy: 但是,如果您真的要测试,则doSecond()是否已调用doFirst(),则可以将服务包装在间谍程序中,然后在间谍程序上调用验证:

//given
SomeService service = new SomeService();
SomeService spy = Mockito.spy(service);
//when
spy.doSecond();
//then
verify(spy).doFirst();

It sounds like you want to avoid the real doFirst being called in your test? 听起来您想避免在测试中调用真正的doFirst吗? if so, try this... 如果是这样,请尝试...

  //given
    boolean firstCalled = false;
    SomeService fakeService  = new SomeService {
          @Override 
          public void doFirst() {
             firstCalled = true;
          }
    }
 //when
 fakeService.doSecond();

  // then
  assertTrue(firstCalled);

This testing/mocking technique is called 'subclass and override' for obvious reasons. 出于明显的原因,这种测试/模拟技术被称为“子类和替代”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM