Mockito当()不工作时

问题描述 投票:0回答:2

所以我分解了一些代码,使其更通用,也更容易让其他人理解类似的问题

这是我的主要代码:

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

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

@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());

}

正如我所说的代码更复杂我把它分解并缩短了......希望它仍然可读。

我的问题不是我的when().thenReturn()不起作用,因此我的代码不再进一步......我想我的嘲弄由于某种原因不能正常工作。

java unit-testing mocking mockito
2个回答
1
投票

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

this.subject.methodA(name);
Authent authent = Mockito.mock(Authent.class);
when(authent.getPassword()).thenReturn("testPW");

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

Authent authent = Mockito.mock(Authent.class);
when(authent.getPassword()).thenReturn("testPW");
this.subject.methodA(name);

此外,模拟对象是第一步。 如果模拟对象未与测试对象关联,则它将对测试对象没有影响。

你应该这样做:

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
...

1
投票

在调用测试方法之前,必须先进行模拟。此外,您必须将该模拟注入您正在测试的类中。

添加结构注释后,看起来像:

@Test
public void testMethodA() throws Exception {            
    // Arrange
    final String name = "testName";
    Authent authentMock = Mockito.mock(Authent.class);
    when(authentMock.getPassword()).thenReturn("testPW");

    this.subject.setAuthent(authentMock);

    // Act
    this.subject.methodA(name);

    // Assert
    assertEquals(1, logger.infos.size());

}
© www.soinside.com 2019 - 2024. All rights reserved.