응답 테스트

TestResponse 클래스는 테스트 케이스에서 응답을 파싱하고 테스트하는 데 유용한 다양한 함수를 제공합니다. 일반적으로 TestResponse컨트롤러 테스트 또는 HTTP 기능 테스트의 결과로 제공되지만, 임의의 ResponseInterface를 사용하여 직접 생성할 수도 있습니다:

$result = new \CodeIgniter\Test\TestResponse($response);
$result->assertOK();

응답 테스트하기

테스트 결과로 TestResponse를 받았든 직접 생성했든, 테스트에서 사용할 수 있는 다양한 새로운 어설션들이 있습니다.

요청/응답 접근

request()

테스트 중에 설정된 경우 Request 객체에 직접 접근할 수 있습니다:

$request = $results->request();

response()

이를 통해 응답 객체에 직접 접근할 수 있습니다:

$response = $results->response();

응답 상태 확인

isOK()

응답이 “정상”으로 판단되는지 여부에 따라 불리언 true/false를 반환합니다. 이는 주로 200번대 또는 300번대의 응답 상태 코드로 결정됩니다. 리다이렉트가 아닌 경우 빈 본문은 유효하지 않은 것으로 간주됩니다.

if ($result->isOK()) {
    // ...
}

assertOK()

이 어설션은 단순히 isOK() 메서드를 사용하여 응답을 테스트합니다. assertNotOK()은 이 어설션의 반대입니다.

$result->assertOK();

isRedirect()

응답이 리다이렉트 응답인지 여부에 따라 불리언 true/false를 반환합니다.

if ($result->isRedirect()) {
    // ...
}

assertRedirect()

응답이 RedirectResponse의 인스턴스임을 어설션합니다. assertNotRedirect()은 이 어설션의 반대입니다.

$result->assertRedirect();

assertRedirectTo()

응답이 RedirectResponse의 인스턴스이고 목적지가 주어진 URI와 일치하는지 어설션합니다.

$result->assertRedirectTo('foo/bar');

getRedirectUrl()

RedirectResponse에 설정된 URL을 반환하거나, 실패 시 null을 반환합니다.

$url = $result->getRedirectUrl();
$this->assertEquals(site_url('foo/bar'), $url);

assertStatus(int $code)

반환된 HTTP 상태 코드가 $code와 일치하는지 어설션합니다.

$result->assertStatus(403);

세션 어설션

assertSessionHas(string $key, $value = null)

결과 세션에 값이 존재하는지 어설션합니다. $value가 전달된 경우 변수의 값이 지정된 값과 일치하는지도 함께 어설션합니다.

$result->assertSessionHas('logged_in', 123);

assertSessionMissing(string $key)

결과 세션에 지정된 $key가 포함되지 않는지 어설션합니다.

$result->assertSessionMissing('logged_in');

헤더 어설션

assertHeader(string $key, $value = null)

응답에 $key라는 이름의 헤더가 존재하는지 어설션합니다. $value가 비어 있지 않은 경우 값이 일치하는지도 함께 어설션합니다.

$result->assertHeader('Content-Type', 'text/html');

assertHeaderMissing(string $key)

응답에 $key라는 이름의 헤더가 존재하지 않는지 어설션합니다.

$result->assertHeader('Accepts');

DOM 헬퍼

반환된 응답에는 응답 내의 HTML 출력을 검사하는 다양한 헬퍼 메서드가 포함되어 있습니다. 이 메서드들은 테스트의 어설션 내에서 유용하게 사용할 수 있습니다.

see()

페이지의 텍스트가 단독으로 존재하는지, 또는 type, class, id로 지정된 태그 내에 더 구체적으로 존재하는지 여부에 따라 불리언 true/false를 반환합니다:

// Check that "Hello World" is on the page
if ($results->see('Hello World')) {
    // ...
}

// Check that "Hello World" is within an h1 tag
if ($results->see('Hello World', 'h1')) {
    // ...
}

// Check that "Hello World" is within an element with the "notice" class
if ($results->see('Hello World', '.notice')) {
    // ...
}

// Check that "Hello World" is within an element with id of "title"
if ($results->see('Hello World', '#title')) {
    // ...
}

dontSee() 메서드는 정반대입니다:

// Checks that "Hello World" does NOT exist on the page
if ($results->dontSee('Hello World')) {
    // ...
}

// Checks that "Hellow World" does NOT exist within any h1 tag
if ($results->dontSee('Hello World', 'h1')) {
    // ...
}

seeElement()

seeElement()dontSeeElement()는 이전 메서드들과 매우 유사하지만, 요소의 값은 확인하지 않습니다. 대신 페이지에 요소가 존재하는지만 단순히 확인합니다:

// Check that an element with class 'notice' exists
if ($results->seeElement('.notice')) {
    // ...
}

// Check that an element with id 'title' exists
if ($results->seeElement('#title')) {
    // ...
}

// Verify that an element with id 'title' does NOT exist
if ($results->dontSeeElement('#title')) {
    // ...
}

seeInField()

seeInField() 메서드는 이름과 값이 있는 입력 태그가 존재하는지 확인합니다:

// Check that an input exists named 'user' with the value 'John Snow'
if ($results->seeInField('user', 'John Snow')) {
    // ...
}

// Check a multi-dimensional input
if ($results->seeInField('user[name]', 'John Snow')) {
    // ...
}

seeCheckboxIsChecked()

마지막으로, seeCheckboxIsChecked() 메서드를 사용하여 체크박스가 존재하고 선택되었는지 확인할 수 있습니다:

// Check if checkbox is checked with class of 'foo'
if ($results->seeCheckboxIsChecked('.foo')) {
    // ...
}

// Check if checkbox with id of 'bar' is checked
if ($results->seeCheckboxIsChecked('#bar')) {
    // ...
}

seeXPath()

Added in version 4.5.0.

seeXPath()를 사용하면 xpath의 모든 기능을 활용할 수 있습니다. 이 메서드는 DOMXPath 객체를 직접 사용하여 더 복잡한 표현식을 작성하려는 고급 사용자를 위한 것입니다:

// Check that h1 element which contains class "heading" is on the page
if ($results->seeXPath('//h1[contains(@class, "heading")]')) {
    // ...
}

// Check that h1 element which contains class "heading" have a text "Hello World"
if ($results->seeXPath('//h1[contains(@class, "heading")][contains(.,"Hello world")]')) {
    // ...
}

dontSeeXPath() 메서드는 정반대입니다:

// Check that h1 element which contains class "heading" does NOT exist on the page
if ($results->dontSeeXPath('//h1[contains(@class, "heading")]')) {
    // ...
}

// Check that h1 element which contains class "heading" and text "Hello World" does NOT exist on the page
if ($results->dontSeeXPath('//h1[contains(@class, "heading")][contains(.,"Hello world")]')) {
    // ...
}

DOM 어설션

다음 어설션을 사용하여 응답 본문에 특정 요소/텍스트 등이 존재하는지 테스트할 수 있습니다.

assertSee(string $search = null, string $element = null)

페이지에 텍스트/HTML이 단독으로 또는 type, class, id로 지정된 태그 내에 더 구체적으로 존재하는지 어설션합니다:

// Verify that "Hello World" is on the page
$result->assertSee('Hello World');

// Verify that "Hello World" is within an h1 tag
$result->assertSee('Hello World', 'h1');

// Verify that "Hello World" is within an element with the "notice" class
$result->assertSee('Hello World', '.notice');

// Verify that "Hello World" is within an element with id of "title"
$result->assertSee('Hello World', '#title');

assertDontSee(string $search = null, string $element = null)

assertSee() 메서드의 정반대를 어설션합니다:

// Verify that "Hello World" does NOT exist on the page
$results->assertDontSee('Hello World');

// Verify that "Hello World" does NOT exist within any h1 tag
$results->assertDontSee('Hello World', 'h1');

assertSeeInField(string $field, string $value = null)

이름과 값이 있는 입력 태그가 존재하는지 어설션합니다:

// Verify that an input exists named 'user' with the value 'John Snow'
$results->assertSeeInField('user', 'John Snow');

// Verify a multi-dimensional input
$results->assertSeeInField('user[name]', 'John Snow');

JSON 다루기

특히 API 메서드를 사용할 때 응답에 JSON 응답이 포함되는 경우가 많습니다. 다음 메서드들을 사용하여 응답을 테스트할 수 있습니다.

getJSON()

이 메서드는 응답 본문을 JSON 문자열로 반환합니다:

/*
 * Response body is this:
 * ['foo' => 'bar']
 */

$json = $result->getJSON();
/*
 * $json is this:
 * {
 *     "foo": "bar"
 * }
`*/

이 메서드를 사용하여 $response가 실제로 JSON 콘텐츠를 포함하는지 확인할 수 있습니다:

// Verify the response is JSON
$this->assertTrue($result->getJSON() !== false);

참고

결과에서 JSON 문자열이 보기 좋게 들여쓰기(pretty-print)되어 출력된다는 점에 유의하십시오.

assertJSONFragment(array $fragment)

$fragment가 JSON 응답 내에 존재하는지 어설션합니다. 전체 JSON 값과 일치할 필요는 없습니다.

/*
 * Response body is this:
 * [
 *     'config' => ['key-a', 'key-b'],
 * ]
 */

// Is true
$result->assertJSONFragment(['config' => ['key-a']]);

assertJSONExact($test)

assertJSONFragment()와 유사하지만, 전체 JSON 응답을 검사하여 정확한 일치를 보장합니다.

XML 다루기

getXML()

애플리케이션이 XML을 반환하는 경우 이 메서드를 통해 가져올 수 있습니다.