Mockito- nethod中的测试方法



我正在尝试测试我的Utils类。其中一些方法使用其他类方法。我想模拟内部方法的使用,以便测试假定它们有效(为了使其进行实际单元测试,哪个测试特定方法)。

我想测试'buildurl'方法:

 public static String buildUrl(String path, List<Pair> queryParams, DateFormat dateFormat) {
    final StringBuilder url = new StringBuilder();
    url.append(path);
    if (queryParams != null && !queryParams.isEmpty()) {
        // support (constant) query string in `path`, e.g. "/posts?draft=1"
        String prefix = path.contains("?") ? "&" : "?";
        for (Pair param : queryParams) {
            if (param.getValue() != null) {
                if (prefix != null) {
                    url.append(prefix);
                    prefix = null;
                } else {
                    url.append("&");
                }
                String value = Utils.parameterToString(param.getValue(), dateFormat);
                url.append(Utils.escapeString(param.getName())).append("=").append(Utils.escapeString(value));
            }
        }
    }
    return url.toString();
}

buildurl使用我想对测试进行模拟的" parametertostring"(和其他)。所以我尝试了这样的事情:

 @Test
public void testBuildUrl(){
    Utils util = new Utils();
    Utils utilSpy = Mockito.spy(util);
    Mockito.when(utilSpy.parameterToString("value1",new RFC3339DateFormat())).thenReturn("value1");
    List<Pair> queryParams = new ArrayList<Pair>();
    queryParams.add(new Pair("key1","value1"));
    String myUrl = utilSpy.buildUrl("this/is/my/path", queryParams, new RFC3339DateFormat());
    assertEquals("this/is/my/path?key1=value1&key2=value2", myUrl);
}

,但我从Mockito获得MissingMethodInvocationException。因此,我的问题实际上是 - 如何模拟已在测试方法中调用的方法,以及测试的问题。谢谢。

您无法使用标准摩擦图模拟/间谍静态调用。

您将必须使用PowerMockito和以下内容:

@RunWith(PowerMockRunner.class)
@PrepareForTest(Utils.class)    
public class MyClassTest{
    @Test
    public void testBuildUrl(){
         PowerMockito.mockStatic(Utils.class);
         // mock the static method to return certain values
         Mockito.when(Utils.parameterToString("value1",new RFC3339DateFormat()))
             .thenReturn("value1");
         Mockito.when(Utils.escapeString(anyString()).thenReturn(desiredResult);
       // rest of test code
    }

这里还有一些需要阅读的内容 -> powermockito static

我想模拟内部方法的使用,以便测试将假定它们有效(为了使其成为实际的单元测试,哪个测试特定方法)。

Unitests做不是 test 特定方法s。

Unittests测试正在测试的代码的公共可观察行为


如果您认为应该嘲笑一些方法,这可能表明您的设计需要改进。无需制作实用方法static,也许您正在测试的课程必须承担很多责任。

原因 PowerMock 将克服测试中的问题,但恕我直言,PowerMock的使用是对不良设计的投降。

最新更新