0

I have created a factory to provide instance of IMyProcessor based on some boolean flag. The below populates the map with both of my implementations.

@Component
public class MyProcessorFactory {

    private static final Map<String, IMyProcessor> processorServiceCache = new HashMap<>();

    @Value("${processor.async:true}")
    private boolean isAsync;

    public MyProcessorFactory(final List<IMyProcessor> processors) {
        for (IMyProcessor service : processors) {
            processorServiceCache.put(service.getType(), service);
        }
    }

    public IMyProcessor getInstance() {
        IMyProcessor processor = isAsync ? processorServiceCache.get("asynchronous") : processorServiceCache.get("synchronous");
        return processor;
    }
}

I am now trying to write a Unit test using Junit5 but I am struggling to setup the List of implementations:

I have tried the following:

@ExtendWith(MockitoExtension.class)
class ProcessorFactoryTest {

    @InjectMocks
    private MyProcessorFactory myProcessorFactory;


    @Test
    void testAsyncIsReturned() {
        
    }
    
    @Test
    void testSyncisReturned() {}
}

I want to test based on the boolean flag async true/false, the correct implementation is returned.

It will be helpful to see how you write such test cases. I autowire the implementations of the interface as construction injection into a list then add to a map using a string key.

Along with answer, I am open to other ideas/refactorings that may make the testing easier.

M06H
  • 1,675
  • 3
  • 36
  • 76
  • Is there anything blocking you in simply instantiating your factory in the test and passing the mocked list of implementations as the constructor arguments? You don't really need Spring-related things to test this class. – Filip O. Sep 03 '20 at 11:40
  • how would I pass the mocked list to the constructor with the impl? – M06H Sep 03 '20 at 11:44
  • 1
    Your factory constructor accepts a List of Implementations of your interface. You can create your mocked processors using, for example, Mockito, create an array list with those mocks and create an instance of your factory. Than you can proceed with the tests. If you don't know how to set the async/sync field in your factory, this is another question and SO has answers to that in separate threads e.g. https://stackoverflow.com/questions/17353327/populating-spring-value-during-unit-test – Filip O. Sep 03 '20 at 11:48

0 Answers0