Unit testing 如何对inturn从另一个类调用方法的类的方法进行单元测试
嗨,我的班级看起来像这样Unit testing 如何对inturn从另一个类调用方法的类的方法进行单元测试,unit-testing,junit,void,Unit Testing,Junit,Void,嗨,我的班级看起来像这样 public class Class1 { public void method1(Object obj) { // Class 2 makes the restApiCall and result as "SUCCESS" if the HTTP response is 202 Class2 class2 = new Class2(); String result = class2.callRestServi
public class Class1 {
public void method1(Object obj) {
// Class 2 makes the restApiCall and result as "SUCCESS" if the HTTP response is 202
Class2 class2 = new Class2();
String result = class2.callRestService();
System.out.println(result);
}
}
我想为类1编写单元测试,我想通过实际不调用RestAPi来完成,这意味着我想模拟class2.callRestService()方法以“成功”或“失败”的形式返回。如何做到这一点。如果您使用
new
(然后不使用注入),您在测试中总会遇到一些问题
你有两个选择:
new
,并模拟该方法@Test
public void test(){
Class1 class1 = Mockito.spy(new Class1());
Class2 class2 = Mockito.mock(Class2.class);
Mockito.doReturn("your result").when(class2).callRestService();
Mockito.doReturn(class2).when(class1).getClient();
// assert something
}
更多关于
Mockito
如果不添加额外的方法,这是不可能的,正如我写的那样,您可以使用PowerMockito
,但这绝不是一个好主意,只是最后一次机会
public class Class1 {
protected Class2 getClient(){
return new Class2();
}
public void method1(Object obj) {
// Class 2 makes the restApiCall and result as "SUCCESS" if the HTTP response is 202
Class2 class2 = new Class2();
String result = class2.callRestService();
System.out.println(result);
}
}
@Test
public void test(){
Class1 class1 = Mockito.spy(new Class1());
Class2 class2 = Mockito.mock(Class2.class);
Mockito.doReturn("your result").when(class2).callRestService();
Mockito.doReturn(class2).when(class1).getClient();
// assert something
}