我在我的应用程序中使用 spring,我想为我的所有类编写单元测试。我从我的应用程序中调用了几个外部 Web 服务,并且我想使用 Mockito 来模拟它们,因为我只想测试我的功能。
假设我有以下情况
这是我的网络服务接口
public interface MyWebService {
public String getSomeData(int id);
}
我以这种方式使用上述服务
public interface MyService {
int doSomethingElse(String str);
}
public class MyServiceImpl implements MyService {
private MyWebService myWebService;
int doSomethingElse(String str) {
.....
myWebService.getSomeData(id);
...
}
}
public interface MyService1 {
Stirng methodToBeTested();
}
public class Class1 implements MyService1{
@Resource
private MyService myService;
public Stirng methodToBeTested() {
myService.doSomethingElse("..");
}
}
我写了如下的uint测试用例。我在这里监视 MyService 以便运行单元测试。
public class class1Test {
@Spy
MyService myService;
@Resource
@InjectMocks
Class1 class1;
public void setUPTest() {
MockitoAnnotations.initMocks(this);
Mockito.doReturn(123).when(myService).doSomethingElse("someString");
}
@Test
public void methodToBeTestedTest() {
this.setUPTest();
...
class1.methodToBeTested();
}
}
当我运行测试时,我看到的是,我从 web 服务中获得了我在存根时提到的值。
谁能帮我这个?