This question has already been asked. The accepted answer doesn't work for me. Here is my code:-
My service is here:
@Service
public class PlantService {
@Autowired
RestTemplate restTemplate;
static String url = "http://some_url_?Combined_Name=Oak";
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
public String getJson() {
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
return response.getBody();
}
}
My unit test
@RunWith(SpringRunner.class)
class PlantServiceTest {
private PlantService plantService;
@Mock
@Autowired
private RestTemplate restTemplate;
@Before
void setUp() {
MockitoAnnotations.initMocks(this);
plantService = new PlantService();
}
@Test
void testGetJsonString() {
// arrange
String expectedJson = "Some json string";
ResponseEntity mocResponse = mock(ResponseEntity.class);
// act
when(restTemplate.getForEntity("url", String.class)).thenReturn(mocResponse);
String actualJson = plantService.getJson();
// assert
assertSame(expectedJson, actualJson);
}
}
When I debug and step into the actual code. I can see restTemplate is null and throws java.lang.NullPointerException
. So how do I unit test this code?
I have tried your code running on my machine.
Please find the test running test class
@RunWith(SpringRunner.class)
class PlantServiceTest {
@InjectMocks
private PlantService plantService;
@Mock
private RestTemplate restTemplate;
String url = "http://some_url_?Combined_Name=Oak";
@BeforeEach
void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
void testGetJsonString() {
// arrange
String expectedJson = "Some json string";
ResponseEntity mocResponse = new ResponseEntity("Some json string", HttpStatus.OK);
// act
when(restTemplate.getForEntity(url, String.class)).thenReturn(mocResponse);
String actualJson = plantService.getJson();
// assert
assertSame(expectedJson, actualJson);
}
}