How Can I Mock a Map of components

Viewed 68

I have a class annotated with @Configuration containing a list of component. In another class, we inject a Map which will contain all the components of this configuration. I'm trying to write unit tests for this class, however I'm getting an issue when I try to mock this Map. Any thoughts ?

@Configuration

@Component Class1 implements MyInterface() {// code}

@Component Class2 implements MyInterface() {// code}

@Component Class3 implements MyInterface() {// code}

In the other class I have :

@Inject Map <key , MyInterface> // during the runtime, this will contain all the component above

Question : I'm writing test for the class which inject the Map, so can I mock this Map, currently, I'm getting unsatisfied dependency.

Thank you for your help !

1 Answers

You can try mocking the Map methods like get or put based on what you are testing. For eg.

Mockito.when(map.get("KEY")).thenReturn("objectYouWantToReturn");
Related