简体   繁体   English

测试一个在mockito中调用该对象的另一个方法的方法

[英]Test a method which calls another method of the object in mockito

I have an interface, ex: 我有一个界面,例如:

interface MyService {
  void createObj(int id)
  void createObjects()
}

I want to test an implementation of the createObjects method, which has body like: 我想测试createObjects方法的实现,它具有如下体:

void createObjects() {
  ...
  for (...) {
     createObj(someId);
  }
}

I have already tested createObj(id) : 我已经测试了createObj(id)

@Test public void testCreate() {
  //given
  int id = 123;
  DAO mock = mock(DAO.class);
  MyService service = new MyServiceImpl(mock);

  //when
  service.createObj(id);

  //verify
  verify(mock).create(eq(id));
}

So I don't want to repeat all test cases for it in the test for createObjects . 所以我不想在createObjects的测试中重复它的所有测试用例。

How can I make sure that another method of the real object was called besides the one I am testing? 除了我正在测试的那个之外,我怎样才能确保调用真实对象的另一个方法?

Use a spy: 使用间谍:

MyService myService = new MyServiceImpl()
MyService spy = spy(myService);
doNothing().when(spy).createObj(anyInt());

// now call spy.createObjects() and verify that spy.createObj() has been called

This is described, like everything else, in the api doc . 与api doc所有其他内容一样被描述。

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

相关问题 如何为使用未知参数调用另一个方法的方法编写 Mockito 测试? - How to write a Mockito test for a method which calls another method with an unknown argument? Mockito 存根 static 方法调用 object 上的方法 - Mockito stub static method which calls a method on an object 调用 void 方法的 CompletableFuture.runAsync() 的 Mockito 测试用例 - Mockito Test case for CompletableFuture.runAsync() which calls void method Junit测试一种方法,该方法调用另一个组件的另一个void方法 - Junit test for a method which calls another void method of another component Mockito调用对象的equals()方法 - Mockito calls Object's equals() method Mockito Java:如何测试调用其他类以检索值的方法 - Mockito Java: How to test a method which calls other class to retrieve value Junit和Mockito:如何测试方法是否调用方法? - Junit and Mockito: How to test whether a method calls a method? 在调用 void ServiceImplementationLayer 方法的 JUnit 测试用例上抛出 Mockito UnfinishedStubingException - Mockito UnfinishedStubbingException thrown on a JUnit test case which calls a void ServiceImplementationLayer method Mockito JUnit对引发异常的方法进行测试 - Mockito JUnit test on method which throws exception 测试使用Mockito在内部调用私有void方法的方法 - Testing a method which calls private void method inside using mockito
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM