How to mock an interface with two different implementation

Viewed 12938

I have a class I need to test that has two instance of different class but same interface. This is how the codes looks like,

Class to be tested:

@Service
public class MainClass {
   @Resource(name = "aClass")
   private IClass instance1;
   @Resource(name = "bClass")
   private IClass instance2;
}

Other classes:

@Service("aClass")
public class A implements IClass {}

@Service("bClass")
public class B implements IClass {}

My Unit Test:

public MainClassTest {
   @InjectMocks
   private MainClass mainClass;

   @Mock
   private IClass instance1;
   @Mock
   private IClass instance2;

   @Test
   public void test() {...}
}

When I run the test, both instance1 and instance2 are null since they are not mocked. This doesn't happen when the interface has only one implementation.

Any idea how to handle this?

Thanks, Angelo

2 Answers
Related