使用Mockito模拟两个相同类型的对象 [英] Mocking two objects of the same type with Mockito

查看:160
本文介绍了使用Mockito模拟两个相同类型的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Mockito编写单元测试,并且在模拟注入的类时遇到了问题.问题在于,两个注入的类是同一类型,并且仅通过它们的@Qualifier注释进行区分.如果我尝试简单地模拟SomeClass.class,则不会插入该模拟,并且在我的测试中该对象为null.如何模拟这些对象?

I'm writing unit tests using Mockito and I'm having problems mocking the injected classes. The problem is that two of the injected classes are the same type, and only differentiated by their @Qualifier annotation. If I tried to simply mock SomeClass.class, that mock is not injected and that object is null in my tests. How can I mock these objects?

public class ProfileDAL {

    @Inject
    @Qualifier("qualifierA")
    private SomeClass someClassA ;

    @Inject
    @Qualifier("qualifierB")
    private SomeClass someClassB ;

    //...various code, not important
}

@RunWith(MockitoJUnitRunner.class)
public class ProfileDALLOMImplTest {

    @InjectMocks
    private ProfileDALLOMImpl profileDALLOMImpl = new ProfileDALLOMImpl();

    @Mock
    private SomeClass someClassA;
    @Mock
    private SomeClass someClassB;

    private SomeResult mockSomeResult = mock(SomeResult.class);

    @Test
    public void testSomeMethod() {
        when(someClassA .getSomething(any(SomeArgment.class)).thenReturn(mockSomeResult);
        Int result = profileDALLOMImpl.someTest(This isn't relevant);
    }

 }

推荐答案

我尝试使用JUnit在Mockito 1.9.5中模拟两个具有相同类型的对象,并且它可以正常工作.

I have tried mocking two objects with the same type with Mockito 1.9.5 using JUnit and it works.

请参阅: http://static.javadoc.io/org.mockito/mockito-core/1.9.5/org/mockito/InjectMocks.html

文档中的相关类型信息:

Relevant type info from the doc:

字段注入;模拟将首先按类型解析,然后,如果存在多个相同类型的属性,则按字段名称和模拟名称的匹配进行解析."

"Field injection; mocks will first be resolved by type, then, if there is several property of the same type, by the match of the field name and the mock name."

这似乎表明您应该在两个相同类型的模拟中使模拟名称与所有模拟的字段名称匹配:

And this one which seems to say you should make the mock name match the field name for all your mocks when you have two of the same type:

注1:如果具有相同类型(或相同擦除)的字段,最好使用匹配的字段来命名所有@Mock带注释的字段,否则Mockito可能会造成混淆,并且注入不会发生."

"Note 1: If you have fields with the same type (or same erasure), it's better to name all @Mock annotated fields with the matching fields, otherwise Mockito might get confused and injection won't happen."

也许后一个人在咬你吗?

Perhaps this latter one is biting you?

这篇关于使用Mockito模拟两个相同类型的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆