Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking two objects of the same type with Mockito

Tags:

mockito

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

 }
like image 532
tamuren Avatar asked Mar 18 '13 19:03

tamuren


1 Answers

Just confirmed what Splonk pointed out and it works that way in Mockito 1.9.5, as soon as I removed one of the mocked classes, it failed.

So, in your case, make sure you have both of the mocked classes with the same name as in the class in your test:

@Mock
private SomeClass someClassA;
@Mock
private SomeClass someClassB;
like image 113
hesparza Avatar answered Nov 10 '22 01:11

hesparza