PHPUnit test
환경
OS : Window7
PHP : 7.2
Apache: 2.4
package : PHPUnit
Framework: Laravel
시작
기본적으로 laravel에서 테스트를 지원하고 있다.
라라벨 설치 후 폴더를 보면 tests 폴더가 존재 하는 것을 볼 수 있다.
테스트 생성
c:\project>php artisan make:test UserTest
* 옵션으로 - - unit 을 넣을 경우 unit 테스트 폴더 쪽으로 이동을 하게 된다 .
(기본은 feature 폴더에 생성)
Unit? Feature? 테스트
단위(Unit)테스트
프로그래머 관점에서 작성됩니다. 클래스의 특정 메소드 (또는 유닛)가 일련의 특정 태스크를 수행하도록 보장됩니다.
기능(Feature)테스트
사용자의 관점에서 작성됩니다. 그들은 사용자가 기대하는대로 시스템이 작동하는지 확인합니다.
테스트 코드
- Clac라는 계산 클래스를 만들고 간단한 테스트를 진행해보겠다.
/app/Model/Calc.phpnamespace App\Model;
class Calc{
public function add($a, $b){
return $a+$b;
}
public function sub($a, $b){
return $a-$b;
}
public function mul($a, $b){
return $a*$b;
}
public function div($a, $b){
return $a/$b;
}
}/tests/Feature/Usertest.phpuse App\Model\Calc;
class UserTest extends TestCase
{
public function setUp(){
parent::setUp();
$this->arr = [1,2,3];
}
public function testBasic() : array
{
$stack = [];
$this->assertEmpty($stack);
$this->assertSame($this->arr, [1,2,3]);
return $stack;
}
/**
* @depends testExample
*/
public function testDepends() : void
{
$this->assertTrue(false,"testDepends test 2");
}
/**
* @depends testBasic
*/
public function testExample(array $stack) : void
{
$Clac = new Calc();
array_push($stack, 'foo');
$this->assertSame($Clac->add(1,2), 3, "add Test");
$this->assertTrue($Clac->add(1,2) == 3,"add Test");
$this->assertNotEmpty($stack,"Array is not empty");
//$this->assertSame($Clac->mul(2,5), 5, "mul Test");
//$this->assertInstanceOf(Clac::class, $Clac->add);
}
}
- 테스트는 cmd 에서 phpunit 라고 명령어를 입력하면 결과를 던져준다
- setUp메서드는 기본적으로 테스트 케이스 클래스 에서 기본셋업을 할때 이용을 하며, parent::setUp();를 꼭 실행시켜줘야된다.
- assert___ 형태의 메서드를 띄며 여기에서 다양한 테스트 케이스와 메서드, 문서를 찾아 볼 수 있을것이다.
테스트실행
- cmd창에서 ‘phpunit’ 이라는 명령어를 이용하면 된다.
- /tests/ 안에 있는 모든 클래스가 테스트 된다. - 특정 클래스만 테스트 할 경우 ‘phpunit 네임스페이스 클래스’의 형태로 이용
ex>phpunit Tests\Unit\UserTest
기타
- 일반적은 값에 대한 테스트 이외에도 header, session, file 등 다양한 테스트가능
- 어노테이션을 이용하여 더 확장적으로 이용 가능(after, befor, dedepends 등)
- Database Testing , Code Coverage Analysis 등 다양한 기능 이용 가능
참고
- laravel phpunit
- https://laravel.kr/docs/5.6/testing - phpunit
- https://phpunit.readthedocs.io/en/7.1/writing-tests-for-phpunit.html - phpunit Anotation
- http://phpunit.readthedocs.io/en/7.1/annotations.html