java – 不能@InjectMocks属性调用Mockito的方法然后返回?

本周我开始使用Mockito,我有一个问题需要了解@InjectMocks字段.

我有一个类似A的A类:

public class A {

    public B b;

    public C c;

    public String string;

}

当我在Mockito的JUnit测试中使用它时,我称之为:

@RunWith(MockitoJUnitRunner.class)
public class Test {

    @Mock
    B b;

    @Mock
    C c;

    @InjectMocks
    A a;

    ...

}

但我想设置字符串属性!我试试这样:

Mockito.when(a.getString()).thenReturn("STRING");

但是,测试会抛出异常:

org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be ‘a method call on a mock’.
For example:
when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods. Those methods cannot be stubbed/verified.
2. inside when() you don’t call method on mock but on some other object.
3. the parent of the mocked class is not public. It is a limitation of the mock engine.

我可以做其他事来设置这个字段吗?

解决方法:

Can I do something else to set this field?

是的,您可以使用@Spy注释您的字段,如下所示:

@Spy
@InjectMocks
A a;

然后你就可以做Mockito.when(a.getString()).thenReturn(“STRING”);

实际上,当它仅使用@InjectMocks进行注释时,Mockito不会模拟它,默认情况下会创建A类的正常实例,这样就不能在其上使用Mockito.when().作为解决方法,您可以要求Mockito使用@Spy对其进行部分模拟.

您实际获得的例外是由于错误消息中提供的案例#2:

inside when() you don’t call method on mock but on some other object.

上一篇:java – 模拟bean依赖关系的NoSuchBeanDefinitionException


下一篇:如何模拟Springockito模拟的行为?