I am new to JUnit and unit testing in java. I am having an issue while testing my code. Any help is appreciated.
My java class: AService.java
@Service
public class AService {
@Autowired
private ServiceB serviceB;
@Autowired
private Gson gson;
public MyEntity getEntity() {
String jsonResponse = serviceB.getResponse();
return gson.fromJson(jsonResponse, MyEntity.class);
}
}
My test class: AServiceTest.java
@ExtendWith(MockitoExtension.class)
public class AServiceTest {
@Mock
private ServiceB serviceB;
@Autowired
private Gson gson;
@InjectMocks
private AService aService;
@Test
public void getEntityTest() {
String serviceBResponse = "{\"id\":55,\"name\":\"My entity\",\"address\":\"XYZ\"}";
when(serviceB.getResponse()).thenReturn(serviceBResponse);
MyEntity entity = aService.getEntity();
assertEquals("My entity", entity.getName());
}
}
This is giving NullPointerException because gson object is not getting initialized. Also we can not mock gson as Gson class is final.
How can I test this code. I am using spring boot and junit5.