gpt4 book ai didi

java - 如何测试需要外部休息调用的方法?

转载 作者:行者123 更新时间:2023-11-30 02:36:08 25 4
gpt4 key购买 nike

我想对一种通过外部访问管理基础设施登录用户的方法进行单元测试。我不知道如何模拟 Response 响应 对象。

这是我打算测试的代码:

public String login(final String username, final String password) {
String baseUrl = getOpenAMApiBaseUrl();
String path = "/openam/json/authenticate";

// Response NEEDS TO BE MOCKED SOMEHOW
Response response = jaxClient.target(baseUrl + path)
.request(MediaType.APPLICATION_JSON_TYPE)
.header(HttpHeaderField.OPENAM_USERNAME, username)
.header(HttpHeaderField.OPENAM_PASSWORD, password)
.post(Entity.json(null));

int status = response.getStatus();
String jsonResponse = response.readEntity(String.class);

if (status == Response.Status.OK.getStatusCode()) {
try (JsonReader jsonReader = Json.createReader(new StringReader(jsonResponse))) {
JsonObject jsonObject = jsonReader.readObject();
String token = jsonObject.getString("tokenId");
LOGGER.info("{} have successfully logged in", username);
return token;
} catch (NullPointerException e) {
LOGGER.info("login failed, invalid json response for {}/{}", username, password);
return null;
}
}

String message = "an error occurred during logging in, http status: {}, user: {}/{}";
if (status == Response.Status.UNAUTHORIZED.getStatusCode()) {
message = "invalid credentials, http status: {}, user: {}/{}";
}
LOGGER.info(message, status, username, password);
return null;
}

最佳答案

理想情况下,您必须模拟从 jaxClient.target 方法开始的所有调用,但在这种情况下,由于生成模拟需要很长的链,我建议使用以下两个选项之一:

1)(首选) - 将响应的创建提取到仅专门从事该特定操作的新类。

然后,您可以将该类声明为被测类的依赖项,然后使用配置为返回某个 Response 对象的构建器方法简单地注入(inject)它的模拟。

2) 您可以在类中创建包级方法,如下所示:

Response buildResponse(){
String baseUrl = getOpenAMApiBaseUrl();
String path = "/openam/json/authenticate";

// Response NEEDS TO BE MOCKED SOMEHOW
Response response = jaxClient.target(baseUrl + path)
.request(MediaType.APPLICATION_JSON_TYPE)
.header(HttpHeaderField.OPENAM_USERNAME, username)
.header(HttpHeaderField.OPENAM_PASSWORD, password)
.post(Entity.json(null));
}

然后 @Spy 测试您的类并模拟该方法以返回您想要的响应:

@Spy
ClassUnderTest classUnderTest;

@Mock
Response responseMock;

@Before
public void init(){
MockitoAnnotations.initMocks(this);
}

@Test
public void test(){
doReturn(responseMock).when(classUnderTest).buildResponse();

// Act

classUnderTest.login(login,pass);

// Assertions
}

关于java - 如何测试需要外部休息调用的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43025893/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com