CodeGym/Java Course/모듈 3/JUnit에서 테스트 환경 설정

JUnit에서 테스트 환경 설정

사용 가능

3.1 주석 @BeforeEach, @AfterEach

이전 예에서 각 메서드에서 개체를 생성하는 코드를 작성해야 했습니다.계산자.

물론 이것은 한 줄에 불과하지만 실제 시스템을 테스트해보면 수십 줄의 코드가 필요할 수 있는 여러 개체를 만들고 구성해야 하는 상황이 자주 발생합니다. 예:

//Create an HttpClient object
   HttpClient client = HttpClient.newBuilder()
    	.version(Version.HTTP_1_1)
    	.followRedirects(Redirect.NORMAL)
        .connectTimeout(Duration.ofSeconds(20))
    	.proxy(ProxySelector.of(new InetSocketAddress("proxy.example.com", 80)))
        .authenticator(Authenticator.getDefault())
    	.build();

   //Create an HttpRequest object
  HttpRequest request = HttpRequest.newBuilder()
     .uri(new URI("https://codegym.cc"))
     .headers("Content-Type", " application/octet-stream")
     .POST( HttpRequest.BodyPublishers. ofInputStream ( () -> is; ))
     .build();

   //Call the send() method
   HttpResponse response = client.send(request, BodyHandlers.ofString());
   System.out.println(response.statusCode());
   System.out.println(response.body());

위의 예에서 개체를 만들고 구성했습니다.Http클라이언트send() 메서드를 테스트하고 싶습니다 .

매번 테스트 메서드에서 개체 생성을 작성하지 않도록Http클라이언트, 별도의 메서드로 이동하고 특별한 @BeforeEach 주석을 지정할 수 있습니다 . 그런 다음 Junit은 각 테스트 메서드 전에 이 메서드를 호출합니다. 예:

class HttpClientTest {
     	public HttpClient client;

   	@BeforeEach
    	public void init(){
   	   client = HttpClient.newBuilder()
   	        .version(Version.HTTP_1_1)
   	        .followRedirects(Redirect.NORMAL)
   	        .connectTimeout(Duration.ofSeconds(20))
   	        .proxy(ProxySelector.of(new InetSocketAddress("proxy.example.com", 80)))
   	        .authenticator(Authenticator.getDefault())
   	        .build();
    	}

   	@Test
    	public void send200() throws Exception {
     	   //Create an HttpRequest() object
         	HttpRequest request = HttpRequest.newBuilder(new URI("https://codegym.cc")).build();

     	   //Call the send() method
     	   HttpResponse response = client.send(request, BodyHandlers.ofString());
        	assertEquals(200, response.statusCode());
        }

   	@Test
    	public void send404() throws Exception {
     	   //Create an HttpRequest() object
         	HttpRequest request = HttpRequest.newBuilder(new URI("https://codegym.cc/unknown")).build();

     	   //Call the send() method
     	   HttpResponse response = client.send(request, BodyHandlers.ofString());
        	assertEquals(404, response.statusCode());
    	}
}

또한 다음 테스트 메서드 이후에 매번 호출되는 특수 메서드를 생성하고, 사용된 리소스를 정리하고 , 로그에 무언가를 기록하는 등의 작업을 수행할 수 있습니다. 이러한 메서드는 @AfterEach 주석으로 표시해야 합니다 .

3개의 테스트 메서드 test1() , test2()test3() 이 있는 경우 호출 순서는 다음과 같습니다.

  • 전에 각 방법
  • 테스트1()
  • AfterEach 메서드
  • 전에 각 방법
  • 테스트2()
  • AfterEach 메서드
  • 전에 각 방법
  • 테스트3()
  • AfterEach 메서드

3.2 주석 @BeforeAll, @AfterAll

JUnit을 사용하면 모든 테스트 메서드 전에 한 번 호출되는 메서드를 추가할 수도 있습니다 . 이러한 메서드에는 @BeforeAll 주석을 달아야 합니다 . 또한 짝을 이룬 @AfterAll 주석 도 있습니다 . 그것으로 표시된 메소드는 모든 테스트 메소드 후에 JUnit에 의해 호출됩니다.

모든 것이 어떻게 작동하는지 더 잘 이해할 수 있는 특별한 예를 작성해 봅시다. 계산기를 기본으로 테스트해 보겠습니다.

class CalculatorTest {
    private Calculator calc = new Calculator();

    @BeforeAll
    public static void init(){
        System.out.println("BeforeAll init() method called");
    }

    @BeforeEach
    public void initEach(){
        System.out.println("BeforeEach initEach() method called");
    }

    @Test
    public void add(){
        System.out.println("Testing Addition");
    }

    @Test
    public void sub() {
        System.out.println("Testing Subtraction");
    }

    @Test
    public void mul(){
        System.out.println("Testing Multiplication");
    }

    @Test
    public void div() {
        System.out.println("Testing Division");
    }
}

이 테스트는 콘솔에 다음 텍스트를 인쇄합니다.


BeforeAll init() method called
BeforeEach initEach() method called
Testing Addition
 
BeforeEach initEach() method called
Testing Subtraction
 
BeforeEach initEach() method called
Testing Multiplication
 
BeforeEach initEach() method called
Testing Division
코멘트
  • 인기
  • 신규
  • 이전
코멘트를 남기려면 로그인 해야 합니다
이 페이지에는 아직 코멘트가 없습니다