如何在Springboot应用程序中模拟RestTemplate

问题描述 投票:0回答:1

This question已被询问。接受的答案对我不起作用。这是我的代码:-

我的服务在这里:

@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;

@BeforeEach
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并抛出java.lang.NullPointerException。那么如何对该代码进行单元测试?

spring-boot resttemplate junit5
1个回答
0
投票

您的问题是plantService = new PlantService();您永远不会注入到此selft创建的实例中。

我通常这样做:

@InjectMocks
private PlantService plantService = new PlantService();

@Mock
private RestTemplate restTemplate;

并删除设置方法。

© www.soinside.com 2019 - 2024. All rights reserved.