I am trying to do a JUnit Test. When I do this I get a NullpointerException. Can I solve this problem using Mockito and if so, how?
@Test
public void test() throws Exception {
Class1 class1 = new Class1(100, "TE", "TEST");
Class2 class2 = new Class2();
//I'm mapping class1 to class3 using class2.map, the usecase here is irrelevant for the problem
Mapped<Class3> result = class2.map(class1, Class3.class);
}
Class2 looks something like this:
public Class class2{
@Inject
private EntityMapper entityMapper; //entityMapper: null
public Mapped<T> map(Class1 class1, Class<T> class3){
return this.entityMapper.map(class1, class3);
}
}
When I'm trying to execute my JUnit test, I get a NullpointerException because the entityMapper inside Class class2 is null. So I want to mock the EntityMapper using the Mockito framework but I can't get around this Problem.
CodePudding user response:
Your class2 is currently not properly unit testable. To make it testable, you need to use constructor/method injections so that we can mock and provide dependencies through test cases. See below,
public class Class2{
private EntityMapper entityMapper;
@Inject
public Class2(EntityMapper mapper){
entityMapper = mapper;
}
public Mapped<T> map(Class1 class1, Class<T> class3){
return this.entityMapper.map(class1, class3);
}
}
Then through your test case you can mock and set dependencies as below,
@Test
public void test() throws Exception {
EntityMapper mapper = mock(EntityMapper.class);
Class1 class1 = new Class1(100, "TE", "TEST");
Class2 class2 = new Class2(mapper);
//TODO: Configure result of mocked functions using mockito when-then methods.
Mapped<Class3> result = class2.map(class1, Class3.class);
}
CodePudding user response:
Instead of creating Class2 class2 = new Class2();
in the test()
, you can just use
@Mock
private Class2 class2;
at class level, and if it is a SpringBoot application you can try either @MockBean
or @Mock