这个问题已经被问过了。接受的答案对我不起作用。这是我的代码:-
我的服务在这里:
@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();
}
}
我的单元测试
@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);
}
}
当我调试并进入实际代码时。我可以看到 restTemplate 是 null 并且 throws java.lang.NullPointerException。那么如何对这段代码进行单元测试呢?