Mockito When() 不起作用

Nal*_*ali 0 java unit-testing mocking mockito

因此,我对代码进行了一些分解,使其更通用,也更容易让其他人理解类似的问题

这是我的主要代码:

protected void methodA(String name) {
        Invocation.Builder requestBuilder = webTarget.request();
        requestBuilder.header(HttpHeaders.AUTHORIZATION, authent.getPassword());

            response = request.invoke();

            if (response.equals("unsuccessfull")) {
                log.warn("warning blabla: {} ({})"); 
            } else {
                log.info("info blabla {}");
            }
        } 
    }
}
Run Code Online (Sandbox Code Playgroud)

而我的测试代码如下所示:

@Test
public void testMethodA() throws Exception {            
    final String name = "testName";

    this.subject.methodA(name);

    Authent authent = Mockito.mock(Authent.class);

    when(authent.getPassword()).thenReturn("testPW");
    assertEquals(1, logger.infos.size());

}
Run Code Online (Sandbox Code Playgroud)

正如我所说,代码更复杂,我将其分解并使其更短......希望它仍然可读。

我的问题不是我的when().thenReturn()代码不起作用,因此我的代码无法进一步进行......我想我的模拟由于某种原因无法正常工作。

dav*_*xxx 5

您测试该methodA()方法,但模拟该类Authent并在调用测试方法后记录它的行为:

this.subject.methodA(name);
Authent authent = Mockito.mock(Authent.class);
when(authent.getPassword()).thenReturn("testPW");
Run Code Online (Sandbox Code Playgroud)

这是无能为力的,因为测试方法已经被调用了。
应该以相反的方式完成:

Authent authent = Mockito.mock(Authent.class);
when(authent.getPassword()).thenReturn("testPW");
this.subject.methodA(name);
Run Code Online (Sandbox Code Playgroud)

此外,模拟对象是第一步。
如果模拟对象没有与被测对象关联,那么它不会对被测对象产生任何影响。

你应该这样做:

Authent authent = Mockito.mock(Authent.class);
// record behavior for the mock
when(authent.getPassword()).thenReturn("testPW");

// create the object under test with the mock
this.subject = new Subject(authent);

// call your method to test
this.subject.methodA(name);

// do your assertions
...
Run Code Online (Sandbox Code Playgroud)