Use SpringBoot Junit5

Junit5 basic syntax

Junit5 website junit.org/junit5/

 PDF download.

annotation

JUnit Jupiter supports the following annotations for configuring the testing and extension framework.

Unless otherwise noted, all core comments are located in the junit-Jupit-API package org.junit.jupit.api in the module.

annotations describe
@Test The presentation method is the test method. Unlike JUnit 4’s @test annotation, this annotation does not declare any attributes, because the Test extensions in JUnit Jupiter operate on their own proprietary annotations. These methods areInherited,Unless they arecover.
@ParameterizedTest The way to express it isParametric test. These methods areInherited,Unless they arecover.
@RepeatedTest The way to express it isRepeat the testTest template. These methods areInherited,Unless they arecover.
@TestFactory The way to express it isDynamic testingTest factory. These methods areInherited,Unless they arecover.
@TestTemplate The way to express it isThe test casetheThe template,Designed to be registered underThe providerReturns the number of call contexts called multiple times. These methods areInherited,Unless they arecover.
@TestMethodOrder Used to configure the test class for annotationsTest method execution order; This class of annotations is similar to JUnit 4’s @fixMethodOrderinherited.
@TestInstance Used to configure for annotated test classesTest the instance life cycle. Such comments areinherited.
@DisplayName Declare customizations of test classes or test methodsThe display name. This type of comment will not beinheritance.
@DisplayNameGeneration Declare a custom for the test classDisplay name generator. Such comments areinherited.
@BeforeEach Indicates that the annotated method should be in the current classeach,,, or methodbeforeImplementation; Similar to JUnit 4. These methods areInherited,Unless they arecover. @Test@RepeatedTest@ParameterizedTest@TestFactory@Before
@AfterEach The method representing the annotation should be executedafter each@test, @REPEATedTest, @parameterizedTest, or @TestFactory methods in the current class; Similar to JUnit 4’s @after. These methods areInherited,Unless they arecover.
@BeforeAll The method representing the annotation should be executedbefore all@test, @REPEATedTest, @parameterizedTest, and @TestFactory methods in the current class; The @beforeClass method similar to JUnit 4 isinherited(Unless they arehiddenorcover) and must be static (unless “per class” is used)Test the instance life cycle).
@AfterAll The method representing the annotation should be executedafter All of the@test, @REPEATedTest, @parameterizedTest, and @TestFactory methods in the current class; This is similar to JUnit 4’s @afterClassinherited(Unless they arehiddenorcover) and must be static (unless “per class” is used)Test the instance life cycle).
@Nested Indicates that the annotated class is non-staticNested test classes. The @beforeAll and @Afterall methods cannot be used directly in @nested test classes unless “every class” is usedTest the instance life cycle. This type of comment will not beinheritance.
@Tag Used to declare at the class or method levelFilter the labels of the tests; Similar to test groups in TestNG or categories in JUnit 4. Such annotations are at the class levelinheritance, but not at the method levelinheritance.
@Disabled Used fordisableTest classes or test methods; Similar to @ignore in JUnit 4. This type of comment will not be usedinheritance.
@Timeout Used to fail a test if the execution of a test, test factory, test template, or lifecycle method exceeds a given duration. Such comments areinherited.
@ExtendWith Used toThe statementwayRegister extensions. Such comments areinherited.
@RegisterExtension Used to pass fields toprogrammingwayRegister extensions. These fields areInherited,Unless they arehidden.
@TempDir Used in a lifecycle method or test method via field injection or parameter injectionThe temporary directory; It is in the org.junit.jupiter. Api.io package.

@parameterizedtest a ParameterizedTest

Build the parameters to test with @valuesource @csvSource

@nullsource: provides Null arguments @emptysource: provides Null arguments String list map array

@Nullandemptysource Compositional annotation combines @nullSource with @emptysource

Such as test palindrome demo

@ParameterizedTest 
@ValueSource(strings = { "racecar", "radar", "able was I ere I saw elba" }) 
void palindromes(String candidate) { 
    assertTrue(StringUtils.isPalindrome(candidate)); 
}
Copy the code

Palindrome method

public static boolean isPalindrome(String str)
{
  if(str==null||str.length()==0)
  {
    throw new RuntimeException("String is empty");
  }
  int mid=(str.length()-1) /2;
  for(int i=0; i<=mid; i++) {if(str.charAt(i)! =str.charAt(str.length()-1-i))
    {
      return false; }}return true;
}
Copy the code

├─ (String) ├─ [1] candidacy =radar ├─ [2] candidacy =radar ├─ [3] candidacy =able was I ere I saw Elba ✔

@ CsvSource sample

@ParameterizedTest(name = "{0} + {1} = {2}")
@CsvSource({ "0, 1, 1", "1, 2, 3", "49, 51, 100", "1, 100, 101" })
void add(int first, int second, int expectedResult) {
  Calculator calculator = new Calculator();
  String express = StrUtil.format("{} + {}",first,second);
  // hutool calculator
  assertEquals(expectedResult, calculator.calculate(express),
      () -> first + "+" + second + " should equal " + expectedResult);
}
Copy the code

➤ ➤ 0 + 1 = 1 ➤ 1 + 2 = 3 ➤ 49 + 51 = 100 ➤ 1 + 100 = 101

@csvSource ({“apple, banana”}) “apple”, “banana” @csvSource ({“apple, ‘lemon, lime'” }) “apple”, “lemon, lime” @CsvSource({ “apple, ”” }) “apple”, “” @CsvSource({ “apple, ” }) “apple”, null @CsvSource(value = { “apple, banana, NIL” }, nullValues = “NIL”) “apple”, “banana”,null

@csvfilesource (resources = “/two-column. CSV “, numLinesToSkip = 1)

@timeout The test program fails to run after the Timeout period

@Test
@Timeout(value = 200,unit = TimeUnit.MILLISECONDS)
void timeout(a){
  ThreadUtil.sleep(1000);
}
Copy the code

@displayname DisplayName you can enter emoticons. Isn’t that funny

@Test
@ DisplayName (" ╯ ╯ ° / °) ")
void testWithDisplayNameContainingSpecialCharacters(a) {}@Test
@ DisplayName (" 😱 ")
void testWithDisplayNameContainingEmoji(a) {}Copy the code

Assertions Assertions Assertions class provides some assertion method import static org. Junit. Jupiter. API. Assertions. AssertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTimeout; import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; import static org.junit.jupiter.api.Assertions.assertTrue;

Repeat test @REPEATedTest to execute the same test for many times, such as @timeout test service time, test content has random variables, run the test for many times. @RepeatedTest(value = 10, name = “{displayName} {currentRepetition}/{totalRepetitions}”) @DisplayName(“Repeat!” ) void customDisplayName(TestInfo testInfo) { // assertEquals(“Repeat! 1/10”, testInfo.getDisplayName()); }

@ TestFactory test method combined with DynamicTest factory produce the following generated two test methods @ TestFactory Collection dynamicTestsFromCollection () {return Arrays.asList( dynamicTest(“1st dynamic test”, () -> assertTrue(isPalindrome(“madam”))), dynamicTest(“2nd dynamic test”, () -> assertEquals(4, calculator.multiply(2, 2))) ); }

SpringBoot test introduces maven dependency org.springframework.boot spring-boot-starter-test test

@SpringBooTtest loads the springBoot context, and then @AutoWired can directly inject @AutoConfigURemockMVC with beans in the Spring container. Inject @springbooTtest @AutoConfiguRemockMVC Class SkyControllerTest {

@Autowired
  MockMvc mockMvc;

  @Test
  void sky (a) throws Exception {
    MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/sky"))
        .andDo(MockMvcResultHandlers.print())
        .andExpect(MockMvcResultMatchers.status().isOk())
        .andReturn();
    String content = mvcResult.getResponse().getContentAsString();
    System.out.println(content);
  }

  @Test
  void deliver (a) throws Exception {
    MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/deliver").param("box"."iphone")) .andDo(MockMvcResultHandlers.print()) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn(); String content = mvcResult.getResponse().getContentAsString(); System.out.println(content); }}Copy the code

You can manually generate a MockMvc object without @AutoConfiguRemockMVC. MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();