Mockito:使用 "thenReturn" 中的方法到 return 模拟不起作用

Mockito: using a method in "thenReturn" to return a mock doesn't work

我遇到了我认为可能是 Mockito 错误的问题,但想知道是否还有其他人可以阐明为什么此测试不起作用。

基本上,我有两个对象,像这样:

public class FirstObject {
    private SecondObject secondObject;
    public SecondObject getSecondObject() { return secondObject; }
}

public class SecondObject {
    private String name;
    public String getName() { return name; }
}

第一个对象是通过注释和 before 方法模拟的:

@Mock
FirstObject mockedFirstObject;

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
}

第二个对象在方法中模拟:

public SecondObject setupMockedSecondObject() {
    SecondObject secondObject = Mockito.mock(SecondObject.class);
    Mockito.when(secondObject.getName()).thenReturn("MockObject");
    return secondObject;
}

thenReturn 包含对此方法的直接调用以设置和获取第二个对象的模拟时,失败:

@Test
public void notWorkingTest() {
    Mockito.when(mockedFirstObject.getSecondObject()).thenReturn(setupMockedSecondObject());
    Assert.assertEquals(mockedFirstObject.getSecondObject().getName(), "MockObject");
}

但是,当将相同方法返回的模拟分配给 thenReturn 中使用的局部变量时,它起作用了:

@Test
public void workingTest() {
    SecondObject mockedSecondObject = setupMockedSecondObject();
    Mockito.when(mockedFirstObject.getSecondObject()).thenReturn(mockedSecondObject);
    Assert.assertEquals(mockedFirstObject.getSecondObject().getName(), "MockObject");
}

我们是不是做错了什么,或者这确实是 Mockito 中的 bug/limitation?这是否不起作用?

这确实是Mockito的局限性,参考in their FAQ:

Can I thenReturn() an inlined mock()?

Unfortunately you cannot do this:

when(m.foo()).thenReturn(mock(Foo.class));
//                         ^

The reason is that detecting unfinished stubbing wouldn't work if we allow above construct. We consider is as a 'trade off' of framework validation (see also previous FAQ entry). However you can slightly change the code to make it working:

//extract local variable and start smiling:
Foo foo = mock(Foo.class);
when(m.foo()).thenReturn(foo);

如上所述,解决方法是将所需的返回值存储在局部变量中,就像您所做的那样。

我的理解是 Mockito 会在您每次调用其方法时验证您对它的使用。在正在进行的存根过程中调用另一个方法时,您将破坏其验证过程。

@Test
public void testAuthenticate_ValidCredentials() throws FailedToAuthenticateException {

    String username = "User1";
    String password = "Password";
    /*Configure Returning True with when...thenReturn configuration on mock Object - Q5*/
   //Write your code here
    assertTrue(authenticator.authenticateUser(username, password));
}

您不能使用 thenReturn 中的方法,但可以使用 thenAnswer 您的代码将在 when 条件发生后被调用, 不同于基于 thenReturn

的任何解决方法

因此你可以这样写:

@Test
public void nowWorkingTest() {
    Mockito.when(mockedFirstObject.getSecondObject()).thenAnswer(new Answer<Map>() {
        @Override
        public Map answer(InvocationOnMock invocation) {
            return setupMockedSecondObject();
        }
    });
    Assert.assertEquals(mockedFirstObject.getSecondObject().getName(), "MockObject");
}

再找一个例子