본문 바로가기

Web/spring

[Spring framework Testing] 2. Unit Testing

728x90

틀린 해석이 있다면 알려주세요

 

https://docs.spring.io/spring-framework/docs/current/reference/html/testing.html#testing-introduction


 

주말이니까ㅎㅎㅎ

간단하게 스프링 테스트에 대한 공식 문서를 읽어보기로 했다.

 

스프링 공식문서에도 서술하고 있듯이

개발자에게 테스트는 굉장히 중요하고

스프링은 단위테스트를 위한 방법을 잘 설명해주고 있다

오늘은 Unit Test 를 맛보기로 살펴보는 걸로!!

 

 

 

 

2. Unit Testing

Dependency injection  DI 는 기존 EE 개발에서보다 컨테인에 대한 코드 종속성을 줄여야한다.

애플리케이션을 구성하는 POJO는 JUnit 또는 TestNG테스트가 가능해야하며

new 를 사용하거나 다른 컨테이너 없이 연산자를 이용하여 인스턴스화 된 개체를 사용하면 된다.

 

mock object를 사용하여 코드를 격리 후 단위별로 테스트가 가능하다.

 

그리고 스프링에 대한 아키텍쳐 recommendation 을 따르면 더 깔끔한 계층화 및 구성 요소화가 더 쉬운 단위 테스트를 더 잘 이용할 수 있다.

단위 테스트를 하는 동안 db 액세스 없이 DAO나 리포지토리 인터페이스를 이용하여 서비스 계층 테스트를 할 수 있다.

 

 

2.1. Mock Objects

Spring includes a number of packages dedicated to mocking:

세부 내용은 짤막해서 그냥 그대로 복붙하고 읽어보기로

 

2.1.1. Environment

The org.springframework.mock.env package contains mock implementations of the Environment and PropertySource abstractions (see Bean Definition Profiles and PropertySource Abstraction). MockEnvironment and MockPropertySource are useful for developing out-of-container tests for code that depends on environment-specific properties.

2.1.2. JNDI

The org.springframework.mock.jndi package contains a partial implementation of the JNDI SPI, which you can use to set up a simple JNDI environment for test suites or stand-alone applications. If, for example, JDBC DataSource instances get bound to the same JNDI names in test code as they do in a Jakarta EE container, you can reuse both application code and configuration in testing scenarios without modification.

  The mock JNDI support in the org.springframework.mock.jndi package is officially deprecated as of Spring Framework 5.2 in favor of complete solutions from third parties such as Simple-JNDI.

2.1.3. Servlet API

The org.springframework.mock.web package contains a comprehensive set of Servlet API mock objects that are useful for testing web contexts, controllers, and filters. These mock objects are targeted at usage with Spring’s Web MVC framework and are generally more convenient to use than dynamic mock objects (such as EasyMock) or alternative Servlet API mock objects (such as MockObjects).

  Since Spring Framework 6.0, the mock objects in org.springframework.mock.web are based on the Servlet 6.0 API.

The Spring MVC Test framework builds on the mock Servlet API objects to provide an integration testing framework for Spring MVC. See MockMvc.

2.1.4. Spring Web Reactive

The org.springframework.mock.http.server.reactive package contains mock implementations of ServerHttpRequest and ServerHttpResponse for use in WebFlux applications. The org.springframework.mock.web.server package contains a mock ServerWebExchange that depends on those mock request and response objects.

Both MockServerHttpRequest and MockServerHttpResponse extend from the same abstract base classes as server-specific implementations and share behavior with them. For example, a mock request is immutable once created, but you can use the mutate() method from ServerHttpRequest to create a modified instance.

In order for the mock response to properly implement the write contract and return a write completion handle (that is, Mono<Void>), it by default uses a Flux with cache().then(), which buffers the data and makes it available for assertions in tests. Applications can set a custom write function (for example, to test an infinite stream).

The WebTestClient builds on the mock request and response to provide support for testing WebFlux applications without an HTTP server. The client can also be used for end-to-end tests with a running server.

 

 

 

2.2. Unit Testing Support Classes

단위 테스트를 돕는 여러 클래스에 대한 설명이다

 

2.2.1. General Testing Utilities

 

The 

org.springframework.test.util 

package contains several general purpose utilities for use in unit and integration testing.

AopTestUtils is a collection of AOP-related utility methods.

- AOP 관련 유틸리티 메소드들이다

Spring proxy 에 있는 기본 대상 개체의 참조값을 얻을 수 있다.

 

You can use these methods to obtain a reference to the underlying target object hidden behind one or more Spring proxies. For example, if you have configured a bean as a dynamic mock by using a library such as EasyMock or Mockito, and the mock is wrapped in a Spring proxy, you may need direct access to the underlying mock to configure expectations on it and perform verifications. For Spring’s core AOP utilities, see AopUtils and AopProxyUtils.

ReflectionTestUtils is a collection of reflection-based utility methods. You can use these methods in testing scenarios where you need to change the value of a constant, set a non-public field, invoke a non-public setter method, or invoke a non-public configuration or lifecycle callback method when testing application code for use cases such as the following:

  • ORM frameworks (such as JPA and Hibernate) that condone private or protected field access as opposed to public setter methods for properties in a domain entity.
  • Spring’s support for annotations (such as @Autowired, @Inject, and @Resource), that provide dependency injection for private or protected fields, setter methods, and configuration methods.
  • Use of annotations such as @PostConstruct and @PreDestroy for lifecycle callback methods.

TestSocketUtils is a simple utility for finding available TCP ports on localhost for use in integration testing scenarios.

 

 

 

2.2.2. Spring MVC Testing Utilities

The org.springframework.test.web package contains ModelAndViewAssert, which you can use in combination with JUnit, TestNG, or any other testing framework for unit tests that deal with Spring MVC ModelAndView objects.

 

 

ModelAndViewAssert 를 사용하여 테스트할 수 있다

 

https://docs.spring.io/spring-framework/docs/current/reference/html/testing.html#spring-mvc-test-framework

 

 

728x90