Search code examples
javaunit-testingjunitmockito

How to mock @Inject Api-Class with Mockito


I'm trying to test a Java method with Junit,

Unfortunately I can't get any further at one point because the Api class was defended as @Inject

I actually tried everything I could, unfortunately null is always returned and the test fails every time.

    @Inject
    private MemberAPi memberApi;




    NewMember newMember = new NewMember();
    newMember = MemberApi.addMember(new CreateMemberParameterObj (newMember, getId , false, Obj ))

Test: I try to mock it like that e.g.

   @Mock
    private MemberAPi mockedMemberApi;



    when(mockedMemberAPi.addMember(anyObject())).thenReturn(anyObject());





Solution

  • Mock the MemberAPI and the NewMember classes. Use @InjectMocks and Mockito will automatically inject the mockMemberAPI object.

    Here is some code:

    @InjectMocks
    private Blam classToTest; // your class.
    
    @Mock
    private MemberAPi mockMemberAPi;
    
    @Mock
    private NewMember mockNewMember;
    
    @Before
    public void before()
    {
        MockitoAnnotations.openMocks(this);
    
        doReturn(mockNewMember).when(mockMemberAPI).addMember(anyObject());
    }
    

    I use the doReturn().when().xxx(); pattern instead of the when(mockedMemberAPi.addMember(anyObject())).thenReturn(mockMemberAPI); pattern.

    Note: thenReturn(anyObject()); makes no sense because you can't return anyObject().