Mocking the Qualified beans using mockito for a spring-boot application

amith picture amith · Jun 7, 2016 · Viewed 9.1k times · Source

consider my scenario

public class SomeClass {
  @Autowired @Qualifier("converter1") private IConverter converter1;
  @Autowired @Qualifier("converter2") private IConverter converter2;

  public void doSomeAction(String mimeType) {
    converter1.execute();
    converter2.execute();
  }
}

This is my code.

In order to test this

@RunWith(MockitoJUnitRunner.class)
public class SomeClassTest {
  @Mock(name="converter1") IConverter converter1;
  @Mock(name="converter2") IConverter converter2;
  @InjectMocks SomeClass class = new SomeClass();
  @Test
  public void testGetListOfExcelConverters() throws Exception {
    class.doSomeAction("abcd");
  }
}

Here the mocks are not getting injected, please help with the proper mechanism for mocking a qualified beans.

If this is not the right way to code using spring, please let me know the correct method for using this.

Answer

jhericks picture jhericks · Jun 7, 2016

Not sure what error you are getting, but your test class doesn't compile because you have what looks like you intend to be a variable name using the keyword class. This worked for me:

@RunWith(MockitoJUnitRunner.class)
public class SomeClassTest {
    @Mock(name="converter1") IConverter converter1;
    @Mock(name="converter2") IConverter converter2;

    @InjectMocks
    SomeClass clazz = new SomeClass();

    @Test
    public void testGetListOfExcelConverters() throws Exception {
        clazz.doSomeAction("abcd");
        verify(converter1).execute();
        verify(converter2).execute();
    }
}

And by "worked for me" I mean that the test actually ran and passed. Note I added a couple of verify statements to assert that the injected mocks got called.

I used the SomeClass code you provided as-is.