我有一个yml文件,用于存储变量。我正在使用@Value批注在程序中访问这些变量。问题出在我为此类方法编写模拟测试用例时,我的测试方法中出现了空指针异常。我不确定我要去哪里。 我现在正在使用@TestPropertySource。我需要正确的方法。
这是到目前为止我尝试过的。 我的yml文件看起来像这样,其中包含许多属性:
car:
services:
clientId: abcde
authTokenUrl: ....
.....
public Class CarExecution(){
@Value("${car.services.clientId}")
private String clientId;
@Value("${car.services.authTokenUrl}")
private String authTokenUrl;
public String getAccessToken() {
HttpHeaders headers = new HttpHeaders();
headers.set(CONTENT_TYPE, "application/x-www-form-urlencoded");
headers.set(ACCEPT, APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<>("grant_type=password" + "&client_id=" + clientId ,headers);
ResponseEntity<Access> response = restTemplate.exchange(authTokenUrl, HttpMethod.POST, entity,A.class);
return response.getBody().token_type + " " +
response.getBody().access_token;
}
}
@RunWith(MockitoJUnitRunner.class)
@TestPropertySource(properties = {
"car.services.clientId = clientId ","car.services.authTokenUrl = authTokenUrl",
})
public class CarTest {
@Value("${car.services.clientId}")
private String clientId;
@Value("${car.services.authTokenUrl}")
private String authTokenUrl;
mockServer = MockRestServiceServer.createServer(restTemplate);
HttpHeaders headers = new HttpHeaders();
headers.set(CONTENT_TYPE, "application/x-www-form-urlencoded");
headers.set(ACCEPT, APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<>(
"grant_type=password&client_id=null", headers);
authTokenUrl = "";
new ResponseEntity<>("", HttpStatus.OK);
A access = new A();
access.access_token = "token";
access.token_type = "type";
response = new ResponseEntity<>(access, HttpStatus.OK);
Mockito.when(restTemplate.exchange(authTokenUrl, HttpMethod.POST, entity, A.class))
.thenReturn(response);
答案 0 :(得分:1)
问题可能出在您的Runner
类上,因为MockitoJUnitRunner
没有初始化任何bean或@Value
注释。
弹簧的回答是SpringJUnit4ClassRunner
,它确实这些位为你(文档here)。
尝试将@RunWith(MockitoJUnitRunner.class)
替换为@RunWith(SpringJUnit4ClassRunner.class)
。