简体   繁体   English

如何测试作为参数传递给另一个方法内部的方法的值(Java单元测试)?

[英]How do I test the values passed as a parameter to a method inside another method (Java Unit Test)?

Example: 例:

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);
}
}

I want to test that the right values are being set in insideMethod to make sure that the correct parameters are being passed to webService.getResponseWS() This is in Java and I should use unit tests and Mokito. 我想测试在insideMethod中设置了正确的值,以确保将正确的参数传递给webService.getResponseWS()这是Java语言,我应该使用单元测试和Mokito。

Note: I am not testing the webService method. 注意:我没有测试webService方法。 I need to test that the values passed to insideMethod are correct. 我需要测试传递给insideMethod的值是否正确。 Example "John" for name instead of "JohnSm" or "John$%". 以名称“ John”代替名称“ JohnSm”或“ John $%”。

So far I have created a test class, instantiated the class being tested and mocked the webService class. 到目前为止,我已经创建了一个测试类,实例化了要测试的类并模拟了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");

You want to use Mockito.verify() . 您想使用Mockito.verify()

The JavaDoc aor the Mockito Verify Cookbook lists a lot of examples. JavaDoc或Mockito Verify Cookbook列出了很多示例。

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");
    }

}

如果您已经设置了Mockito并正确注入了模拟,那么下面的命令应该可以工作(尽管我手边没有编译器或JVM来检查)。

verify(webService).getResponseWS("John", "J", "Smith", "02-02-1990");

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM