Mocking two objects of the same type with Mockito

前端 未结 3 590
孤城傲影
孤城傲影 2020-12-20 12:58

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 diff

3条回答
  •  情话喂你
    2020-12-20 13:39

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

    See: 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:

    "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?

提交回复
热议问题