示例:
public class myClass {
private WebService webService;
public void process(String delimitedString) {
String[] values = StringUtils.split(delimitedString, "$%");
insideMethod.setFirstName(values[0]);
insideMethod.setMiddleName(values[1]);
insideMethod.setLastName(values[2]);
insideMethod.setBirthDate(values[3]);
webService.getResponseWS(insideMethod.getFirstName,
insideMethod.getMiddleName,
insideMethod.getLastName,
insideMethod.getBirthDate);
}
}
我想测试insideMethod
中是否设置了正确的值,以确保将正确的参数传递给webService.getResponseWS()
这是Java,我应该使用单元测试和Mokito。
注意:我没有测试webService
方法。我需要测试传递给insideMethod
的值是否正确。示例" John"代替" JohnSm"或" John $%"。
到目前为止,我已经创建了一个测试类,实例化了正在测试的类并模拟了webService类。
public class TestClass {
MyClass myClass = new MyClass();
private WebService webService = mock(WebService.class);
public void processTest() {
when(webService.getResponseWS()).thenCallRealMethod();
insideMethod.process("John$%J$%Smith$%02-02-1990");
答案 0 :(得分:2)
您想使用Mockito.verify()
。
JavaDoc和Mockito Verify Cookbook列出了很多例子。
答案 1 :(得分:1)
import static org.mockito.Mockito.verify;
@RunWith(MockitoJUnitRunner.class)
public class TestClass {
@Mock
private WebService webService;
private MyClass myClass = new MyClass();
@Test
public void processTest() {
// inject webService mocked instance into myClass instance, either with a setter
myClass.setWebService(webService);
// or using Mockito's reflection utils if no setter is available
//Whitebox.setInternalState(myClass, "webService", webService);
// call the method to be tested
String input = "input"; // whatever your input should be for the test
myClass.process(input);
// verify webService behavior
verify(webService).getResponseWs(
"expectedInput1", "expectedInput2", "expectedInput3", "expectedInput4");
}
}
答案 2 :(得分:0)
如果您已经设置了Mockito并正确注入了模拟,则以下内容应该有效(尽管我手头没有编译器或JVM来检查)。
verify(webService).getResponseWS("John", "J", "Smith", "02-02-1990");