我正在使用SpringRunner运行Junit mockito测试用例,下面是这个类,我试图编写测试用例,但得到了空对象
public class AccountManager {
public String getToken() throws Exception {
@Autowired
RestClient restClient;
String auth = apiUserPrefix + apiUserName + BatchJobConstants.COLON + apiUserPassword;
byte[] encodedAuth = Base64.encodeBase64(
auth.getBytes(StandardCharsets.UTF_8));
String authHeader = BatchJobConstants.BASIC_SPACE + new String(encodedAuth);
String token= null;
MultiValueMap<String, String> data = new LinkedMultiValueMap<>();
data.add("grant_type", "client_credential");
String accManagerUrl = accManagerHost+":"+accManagerPort+"/"+accManagerResPath;
RestResponseObject responseObject = null;
try {
responseObject = restClient.execute(accManagerUrl, HttpMethod.POST, data, String.class, authHeader);
if (responseObject != null && responseObject.getPayload() != null && responseObject.getStatusCode() == HttpStatus.OK) {
JsonElement responseJson = (JsonElement) responseObject.getPayload();
if (responseJson.isJsonObject()) {
token= responseJson.getAsJsonObject().get(BatchJobConstants.ACCESS_TOKEN).getAsString();
}catch(RunTimeException e) {
//e
}
return token;
}
//Junit测试用例
@RunWith(SpringRunner.class)
public class AccountManagerTest {
@InjectMocks
AccountManager accountManager;
@Mock
RestClient restClient;
@Test
public void getTokenAccMgrSucess() throws Exception {
RestResponseObject restResponseObject = Mockito.mock(RestResponseObject.class);
Mockito.when(restClient.execute(Mockito.anyString(), Mockito.any(HttpMethod.class),
Mockito.anyString(), Mockito.eq(String.class), Mockito.anyString())).thenReturn(restResponseObject);
String token = accountManagerTokenProvider.getToken();
Assert.assertEquals("Token value {} ", null, token);
}
}
但是,即使在嘲笑了这一点之后,下面的代码仍然返回null值,你能帮助如何嘲笑这一点吗。
responseObject = restClient.execute(accManagerUrl, HttpMethod.POST, data, String.class, authHeader);
注意:只有Mockito需要不使用powermockito
对于Autowired字段,您不仅需要模拟它,而且应该将模拟类绑定到spring上下文。您有两个选项:
<1。将模拟类标记为primarybean>
@Configuration
public class TestConfiguration {
@Bean
@Primary
public RestClient restClient() {
return Mockito.mock(RestClient.class);
}
}
2.使用@MockBean注释
@MockBean
RestClient restClient;
更多信息:
https://www.baeldung.com/injecting-mocks-in-spring
https://www.baeldung.com/java-spring-mockito-mock-mockbean
最后只使用了mockito,而不是anyString((,因为Object与仅字符串的不匹配
Mockito.when(restClient.execute(Mockito.any(), Mockito.any(HttpMethod.class),
Mockito.any(), Mockito.eq(String.class), Mockito.any())).thenReturn(restResponseObject);