所以我想測試時的StatusCode爲401以下方法拋出一個異常:斯波克測試沒有設定返回值正確
HttpEntity doGet(HttpGet httpGet) {
# other stuff...
HttpResponse response = this.httpClient.execute(httpGet); // LINE 3
int statusCode = response.getStatusLine().getStatusCode(); // LINE 4
if (statusCode == 401) {
throw new ApiClientException(401, "Recheck your login username & password credentials in the " +
"file Configurations.groovy as they are NOT working.");
}
# other stuff...
}
我現在用的是斯波克測試框架,你可以使用「 >>「來指定對象的方法返回值。所以當代碼response.getStatusLine().getStatusCode()
被調用時,我想控制它在上面的LINE 4上返回401。
我試圖做到這一點的線18以下測試& 19,但它不工作:
def "test doGet(HttpGet httpGet) throws the correct exceptions when given unsuccessful HttpGet instance"() {
given:
def httpGet = new HttpGet("http://sand.api.appnexus.com/member?id=1196");
def httpClient = Stub(HttpClient);
this.apiClient.httpClient = httpClient;
def httpResponseWithStatusCode401 = Stub(HttpResponse);
httpClient.execute(httpGet) >> httpResponseWithStatusCode401; # LINE 18 This response is correctly returning
httpResponseWithStatusCode401.getStatusLine().getStatusCode() >> 401; # LINE 19 this is never returning 401 right now and always 0 instead
when:
ApiClientException expectedException;
try {
this.apiClient.doGet(httpGet);
} catch(ApiClientException expected) {
expectedException = expected;
}
then:
expectedException.getMessage().equals("Recheck your login username & password credentials in the " +
"file Configurations.groovy as they are NOT working.");
}
問題:如何給我做線4回我想要的東西在我的測試LINES 19?
'httpResponseWithStatusCode401'永遠不會在任何地方使用(看起來像缺少'httpClient.execute'的存根)。此外,第18行不是模擬期望(它既沒有'*'也沒有''''),它調用了模擬對象(這可能不是你想要的)。 –
@PeterNiederwieser非常感謝您回答我的問題。我使用存根更新了我的問題,並且無法得到響應返回401.您介意看看嗎? –
@PeterNiederwieser另外我剛剛檢查了你的個人資料,發現你是Spock的創造者,並且在Gradle工作。太棒了!我喜歡使用Spock和Gradle! –