首页 > 解决方案 > 如何应用 toAnswer 方法(模拟测试)?

问题描述

我有一个看起来像这样的方法:

public  class MainClass{
@Autowired
OtherClass otherClass;

public ObjectType1 method1(){
   ObjectType1 object = new ObjectType1();
   object.setField1("field1Value");
   otherClass.method5(object) // method 5 is huge, modifies  the field2 of "object"
   return object; //an object with field1 and field2 modified
}
}

在 mockito 中测试这个的最好方法是什么?在代码/伪代码混合中,我正在我的测试类中寻找类似的东西

@Test
public void testMethod1() {
  MainClass class1 = new MainClass();

  ObjectType1 newObject = class1.method1();
  //in method1, a new ObjectType1 is created, is there a way to mock the calling of method5?

  assertNotNull(newObject.field1);
}

从研究看来 doAnswer 可以解决问题,但是我还没有真正理解我在网上看到的任何示例

标签: javaunit-testingjunitmockingmockito

解决方案


推荐阅读