我目前處於虧損狀態,單元測試了一個調用其中的REST服務的方法,用於向此服務發送狀態消息。休息調用的單元測試
我有這樣的方法:
public void informService(String state, BusinessObject bus) {
Client client = null;
Response response = null;
try {
client = new ResteasyClientBuilder()
.establishConnectionTimeout(10L, TimeUnit.MINUTES)
.socketTimeout(10L, TimeUnit.MINUTES)
.build();
WebTarget target = client.target("my.url");
MyDTO dto = new MyDTO();
dto.state = state;
response = target.request("application/json").put(Entity.json(dto));
boolean ok = handleReturnCode(response.getStatus(), bus.getId());
if (!ok) {
throw new RuntimeException("Invalid status" + response.getStatus());
}
return ok;
} catch (Exception e) {
} finally {
try {
if (response != null) {
response.close();
}
if (client != null)
client.close();
} catch (Exception e) {
}
}
所以該方法有哪個在方法中評估了REST服務的調用。我怎樣才能測試這種行爲?
這真是醜陋的代碼我必須說。要測試這個,你可能想看看PowerMock,它可以幫助你 –
該方法不遵循SOLID原則。將代碼拆分爲resposabilities。不要在方法中構建客戶端,將其作爲參數接收或使用工廠,這樣您就可以嘲笑它並僅測試內部邏輯。單元測試是關於測試方法/類邏輯,而不是與其他類的集成。 –