I’m writing a unit test for a class A which extends class B. I’m using Mockito and I want to mock a org.slf4j.logger both classes to use. The problem is when class A calls on a method from class B, the mocked logger is not injected into class B so I get a NPE. Is there a way to successfully test this?
public class ClassA extends ClassB {
@Inject
private static final Logger LOGGER = LoggerFactory.getLogger(ClassA.class);
public void classAMethod {
LOGGER.debug("u wot m8");
this.classBMethod();
}
public class ClassB {
@Inject
private static final Logger LOGGER = LoggerFactory.getLogger(ClassB.class);
public void classBMethod {
LOGGER.debug("u wot m8");
}
}
public class ClassATest {
@InjectMocks
private ClassA classA = new ClassA
@Mock
private Logger mockLogger;
@Test
public void testClassA() {
classA.classAMethod ();
verify(mockLogger, (times, 2)).debug(Mockito.anyString());
}
}
If you are using Java EE 6 @Inject it will not work outside the CDI container, this is part of the spec. If this is a unit test you have to provide it by yourself.