참고
https://junit.org/junit5/docs/current/user-guide/#overview-what-is-junit-5
JUnit 5 User Guide
Although the JUnit Jupiter programming model and extension model will not support JUnit 4 features such as Rules and Runners natively, it is not expected that source code maintainers will need to update all of their existing tests, test extensions, and cus
junit.org
XPath로 HTML 본문 테스트시
https://www.w3schools.com/xml/xpath_syntax.asp
XPath Syntax
XPath Syntax XPath uses path expressions to select nodes or node-sets in an XML document. The node is selected by following a path or steps. The XML Example Document We will use the following XML document in the examples below.
www.w3schools.com
https://www.freeformatter.com/xpath-tester.html#ad-output
Free Online Tools For Developers - FreeFormatter.com
Free Online Tools For Developers I created this website to help developers by providing them with free online tools. These tools include several formatters, validators, code minifiers, string escapers, encoders and decoders, message digesters, web resource
www.freeformatter.com
그래들
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
Annotations
JUnit4 | JUnit5 | 설명 |
@BeforeClass | @BeforeAll | 테스트 실행 전 최초 1회 실행 (static void) |
@Before | @BeforeEach | 모든 @Test 실행 전에 실행 |
@After | @AfterEach | 모든 @Test 실행 후에 실행 |
@AfterClass | @AfterAll | 테스트 종료 후 마지막 1회 실행 (static void) |
@Ignore | @Disabled | 테스트 실행 제외 |
@RunWith(SpringRunner.class) | @ExtendWith(SpringExtension.class) | Runner 지정 |
@Test | 테스트 케이스 | |
@ParameterizedTest | @ValueSource와 함께 사용 ex) @ParameterizedTest @ValueSource(ints={2,3,4,5,6,Integer.MAX_VLUE}) 파라메터 하나하나를 모두 테스트, @NullSource, @NullAndEmptySource, @CvsSource() name = "{index} {displayName} message = {0} |
|
@RepeatedTest(반복횟수) | RepetitionInfo ri 인자 사용 가능, 반복횟수, 총반복횟수 참조가능 | |
@DisplayName | 테스트 메서드 설명 create_new_study | |
@DisplayNameGeneration | 클래스, 메서드, | |
예외테스트 | assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(()->obj.func()); |
|
@DataJpaTest | 리포지토리 관련 Bean 등록 : JPA 테스트시 사용 JPA테스트시 하이버네이트는 실제 쿼리를 날리지는 않음 RallBack할 걸 알기 때문 테스트에서 쿼리를 보려면, @Test @Rollback(false) 를 함께 사용 |
|
@WebMvcTest | MockMvc 주입 : 컨트롤러 테스트 시 사용 | |
테스트 구조 | // Given : 이런 조건하에서 // When : 이렇게 했을때 // Then : 이렇게 되길 기대한다 |
|
@Import(Config.class) | Config.class에서 필요 @Bean 등록 | |
@TestInstance(Lifecycle.PER_CLASS) | 테스트시 테스트별로 각 인스턴스를 만들어서 테스트 안하고 하나의 인스턴스로 | |
@TestMethodOrder | 각각의 테스트에 실행 순서를 정한다 (MethodOrderer.OrderAnnotation.class)사용시 @Order(숫자)로 지정 가능 |
|
@ExtendWith | @RegisterExtension 으로 Field 에 가져올 수도 있음 |
@WebMvcTest(SampleController.class)
class SampleControllerTest {
@Autowired
MockMvc mockMvc;
@Test
@DisplayName("헬로우월드 테스트")
public void helloWorldTest() throws Exception {
mockMvc.perform(get("/hello"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().string("HelloWorld"));
}
}
@DisplayName("라이프사이클 테스트")
public class LifecycleTest {
@BeforeAll // JUnit 4의 @BeforeClass
static void initAll() {
System.out.println("initAll");
}
@BeforeEach // JUnit 4의 @Before
void init() {
System.out.println("init");
}
@DisplayName("어떤 테스트")
@Test
void someTest() {
System.out.println("someTest");
}
@Disabled("테스트 실행 제외")
@Test
void anyTest() {
System.out.println("anyTest");
}
@AfterEach // JUnit 4의 @After
void tearDown() {
System.out.println("tearDown");
}
@AfterAll // JUnit 4의 @AfterClass
static void tearDownAll() {
System.out.println("tearDownAll");
}
}
@SpringBootTest
@AutoConfigureMockMvc
class SamplConTest{
@Autowired
MockMvc mockMvc;
@Test
public void hello(){ }
}
Assert Method
https://javacan.tistory.com/entry/JUnit-5-Intro
JUnit 5 소개
[갱신] 2018-11-19: junit 5.3.1과 maven-surefire-plugin 2.22.0 버전에 대한 내용 추가 Junit 5 정식 버전이 나왔다. 테스트 코드를 작성하는 개발자 입장에서 JUnit 5를 보면 JUnit 4에 비해 중요한 차이점은..
javacan.tistory.com
assertEquals(expected, actual) | 기대하는값, 실제값, () -> "설명메시지", 실제값이 기대값과 같은지 확인 |
assertNotEquals | assertNotEquals(Object unexpected, Object actual) |
assertTrue(boolean condition) | 다음 조건이 참 인지 확인 |
assertFalse(boolean condition) | |
assertNull(Object actual) | 값이 null인지 아닌지 확인 |
assertNotNull(Object actual) | |
assertTimeout(duration,executalbe) assertTimeoutPreemptively: 특정시간 넘어가면 실행 바로 종료 |
assertTimeout(Duration.ofMillis(100), ()->{ new Study(10); Thread.sleep(300); }); |
fail() | |
@EnabledOnOS @DisabledOnOS @EnabledOnJre @EnabledIfEnvironmentVariable |
|
assertAll(람다식, ...) | 첫번째 람다식이 실패해도 나머지 모든 람다식 테스트 수행 assertAll( () -> assertEquals(2, score.getA()), () -> assertEquals(1, score.getB()) ); |
assertThrows() | @Test void simple() { ArithmeticException exception = assertThrows(ArithmeticException.class, () -> divide(100, 0)); String message = exception.getMessage(); assertEquals("하하하", exception.getMessage()); } private int divide(int op1, int op2) { return op1 / op2; } throw new IllegalArgumentException("limit은 0보다 커야 한다."); |
assumeTrue() assumeFalse() |
인자로 전달받은 값이 true일 경우에만 이후 테스트 진행 @Test void runTest_IfWindonw() { assumeTrue(System.getProperty("os.name").startsWith("Windows")); assertEquals(1, 2); } @Test void runTest_IfLinux() { assumeTrue(() -> System.getProperty("os.name").startsWith("Linux")); assertEquals(1, 2); } |
assumingThat() | 지정한 가정을 충족한 경우 지정한 검증 수행 @Test void runTest() { String osName = System.getProperty("os.name"); assumingThat( osName.startsWith("Linux"), // (1) 가정 boolean 또는 BooleanSupplier () -> assertEquals(1, 2) // (2) 가정을 충족할 때 실행할 코드(Executable 타입) ); assertEquals(1, 1); // (3) } |
@Tag("name") | 클래스, 메소드에 태깅 가능, 그래들이나 메이븐 설정에서 특정 테스트를 제외 가능 그래들 junitPlatform { filters { tags { include 'slow', 'very-slow' exclude 'pay' } } } |
AssertJ, Hemcrest ...
https://umanking.github.io/share/2020/03/07/intellij-gradle-test.html
IntelliJ, Gradle 테스트가 느릴때
Gradle로 테스트 케이스를 작성하는데, cleanTest, CompileJava … 와 같이 여러개의 task를 실행해서 테스트 케이스 동작하는 게 느릴때 해결하는 방법에 대해서 알아보자.
umanking.github.io