2014-07-16 4 views
1

Так что я пытаюсь проверить следующий метод генерирует исключение, когда что 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(), я хочу контролировать, что он возвращает 401 на LINE 4 выше.

Я пытаюсь сделать это на линии 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 вернуть то, что я хочу в моем тесте на ЛИНИЙ 19?

+2

'httpResponseWithStatusCode401' никогда не используется нигде (похоже, что укорачивание' httpClient.execute' отсутствует). Кроме того, строка 18 не является макетным ожиданием (она не имеет '*' или '>>'), она вызывает макет-объект (что, вероятно, не то, что вы хотите). –

+0

@PeterNiederwieser Большое спасибо за ответ на мой вопрос. Я обновил свой вопрос с помощью Stubs и у меня возникли проблемы с ответом на возврат 401. Не могли бы вы взглянуть? –

+0

@PeterNiederwieser Также я только что проверил ваш профиль и заметил, что вы были создателем Спока и работали в Gradle. Это восхитительно! Мне нравится использовать Спок и Грейдл! –

ответ

2

Это, как Вы должны реализовать этот тест:

@Grab('org.spockframework:spock-core:0.7-groovy-2.0') 
@Grab('cglib:cglib-nodep:3.1') 
@Grab('org.apache.httpcomponents:httpclient:4.3.4') 

import spock.lang.* 
import org.apache.http.client.methods.HttpGet 
import org.apache.http.client.HttpClient 
import org.apache.http.HttpEntity 
import org.apache.http.HttpResponse 
import org.apache.http.StatusLine 
import org.apache.http.message.BasicHttpResponse 

class Test extends Specification { 

    def "test doGet(HttpGet httpGet) throws the correct exceptions when given unsuccessful HttpGet instance"() { 
     given: 
     def client = new Client() 
     client.httpClient = GroovyMock(HttpClient) { 
      execute(_) >> new BasicHttpResponse(null, 401, '') 
     } 

     when: 
     client.doGet(GroovyMock(HttpGet)) 

     then: 
     def e = thrown(ApiClientException) 
     e.code == 401 
     e.message == 'Recheck your login username & password credentials in the file Configurations.groovy as they are NOT working.' 
    } 
} 

class ApiClientException extends Exception { 

    def code 
    def msg 

    ApiClientException(code, msg) { 
     this.code = code 
     this.msg = msg 
    } 

    String getMessage() { 
     'Recheck your login username & password credentials in the file Configurations.groovy as they are NOT working.' 
    } 
} 

class Client { 

    def HttpClient httpClient 

    HttpEntity doGet(HttpGet httpGet) { 

     HttpResponse response = httpClient.execute(httpGet) 
     int statusCode = response.getStatusLine().getStatusCode() 
     if (statusCode == 401) { 
      throw new ApiClientException(401, "Recheck your login username & password credentials in the " + 
        "file Configurations.groovy as they are NOT working."); 
     } 
    } 
} 

, что все ясно для вас?

+0

Большое вам спасибо! –

+0

Добро пожаловать! – Opal

Смежные вопросы