Frequent annotations for Spring Boot tests

Record what you have used to test Spring Boot as a reminder

Unit test

@RunWith Various Runner classes can be specified The Runner class controls what kind of test is performed.

@RunWith(SpringRunnner.class) Required when testing with DI

@RunWith(SpringRunnner.class)
public class SampleClassTest {

  @Autowired
 private HogeService hogeService; // Service that is DI

}

--When you want to mock a class to be autowired, rewrite it to @MockBean without using @Autowired.

@RunWith(MockitoJUnitRunner.class) Required if there is a class you want to mock among the classes under test

@RunWith(MockitoJUnitRunner.class)
public class SampleClassTest {

  @Mock
 private HogeService hogeService; // Classes that are unlikely to work

  @Test
 public void Normal system () {

    Fuga fugaMock = mock(Fuga.class);
    when(hogeService.get()).thenReturn(fugaMock);
 /// The return value of get () of HogeService is Fuga class.

    ...

  }
}

--No processing specific to Spring Boot. -@Mock and mock () methods are both mocking processes.

@RunWith(PowerMockRunner.class) Needed when you have to mock static methods

@RunWith(PowerMockRunner.class)
 @PrepareForTest ({HogeService.class}) // Class containing static methods
public class SampleClassTest {

  @Before
  public void setUp() {
    PowerMockito.mockStatic(HogeService.class);
  }

  @Test
 public void Normal system () {

    HogeService hogeMock = mock(HogeService.class);
    Fuga fugaMock = mock(Fuga.class);
    when(hogeMock.get()).thenReturn(fugaMock);
 /// The return value of get () of HogeService is Fuga class.

    ...

  }
}

@DataJpaTest It supports testing only between entities and repositories. Load into class ApplicationContext with @Entity and @Repository.

@AutoConfigureTestDatabase By setting @AutoConfigureTestDatabase (replace = AutoConfigureTestDatabase.Replace.NONE), you can use the DB set in the application.

@TestExecutionListeners You can set up listeners that monitor tests and provide a variety of features.

@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@TestExecutionListeners({
    TransactionalTestExecutionListener.class,
    DbUnitTestExecutionListener.class})
@DbUnitConfiguration(
    dataSetLoader = ReplacementCsvDataSetLoader.class
)
public class RepositoryTest {

  @DatabaseSetup("/sample/")
  @Test
 public void Normal system () {

    ...

  }
}

table-ordering.txt


sample_table

sample_table.csv


id,name,age
1,Tanaka,20
2,Suzuki,24

--TransactionalTestExecutionListener provides transaction management function. --DbUnitTestExecutionListener provides DB related functions such as @DatabaseSetup. --@DatabaseSetup specifies the directory under resource. Table-ordering.txt of the specified directory is read. This time it is described as sample_table, sample_table.csv of the same directory is read and test data is prepared -@DbUnitConfiguration (dataSetLoader = ReplacementCsvDataSetLoader.class) handles DB in CSV format. Required if @DatabaseSetup is done in CSV

Other listeners that are likely to be specified

ServletTestExecutionListener: Provides the ability to configure a mock Servlet API that supports testing the WebApplicationContext.

DirtiesContextBeforeModesTestExecutionListener: Provides the life cycle management function of the DI container used in the test. Called before executing a test class or test method.

DependencyInjectionTestExecutionLiLstener: Provides DI functionality for the instance used in the test.

SqlScriptsTestExecutionListener: Provides the function to execute the SQL specified by @Sql annotation.

Combined test

@SpringBootTest Provides Spring Boot functionality (reads application.properties and yml) By default, the app does not start, but if you set it, it will start.

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestExecutionListeners(
        listeners = {
                TransactionalTestExecutionListener.class,
                DbUnitTestExecutionListener.class},
        mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS
)
@DbUnitConfiguration(
        dataSetLoader = ReplacementCsvDataSetLoader.class
)
public class FunctionalTest {

  @DatabaseSetup("/sample/")
  @Test
 public void Normal system () {

 Resource sampleJson = resourceLoader.getResource ("/ response / normal system.json");
    String jsonText = FileUtils.readFileToString(responseResource.getFile(),UTF_8);

    ResponseEntity actual = testRestTemplate.exchange(
        "/top",
        HttpMethod.GET,
        new HttpEntity<>(null,null),String.class
    );
    String actualText = actual.getBody().toString();
 ... // assert and Verify

  }
}

--Rest API test sample --Place json under resource and get expected value --Execute with testRestTemplate and get the execution value

@AutoConfigureMockMvc Reproduce the operation of Spring MVC. You will be able to test communication between Controller↔︎Views.

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestExecutionListeners(
        listeners = {
                TransactionalTestExecutionListener.class,
                DbUnitTestExecutionListener.class},
        mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS
)
@DbUnitConfiguration(
        dataSetLoader = ReplacementCsvDataSetLoader.class
)
@AutoConfigureMockMvc
public class FunctionalTest {

  @DatabaseSetup("/sample/")
  @Test
 public void Normal system () {

 MvcResult result = mockMvc.perform (get ("/ top")) // URL specification
 .andExpect (status (). isOk ()) // Check HTTP status
 .andExpect (view (). name ("top")) // Check HTML
          .andReturn();

    ...

  }
}

-If you hit / top and status 200 is returned and you can see top.html, it feels OK

Recommended Posts

Frequent annotations for Spring Boot tests
Annotation notes when writing tests for Spring Boot
Spring Boot for annotation learning
Spring Boot for the first time
Use DBUnit for Spring Boot test
Use Spring Test + Mockito + JUnit 4 for Spring Boot + Spring Retry unit tests
WebMvcConfigurer Memorandum of Understanding for Spring Boot 2.0 (Spring 5)
Spring Boot Form
Spring Boot Memorandum
gae + spring boot
Book introduction: Spring Boot Recommended reference book for beginners!
Annotations used in Spring Boot task management tool
Plans to support JDK 11 for Eclipse and Spring Boot
Settings for connecting to MySQL with Spring Boot + Spring JDBC
SPRING BOOT learning record 01
How to set Dependency Injection (DI) for Spring Boot
Spring Boot + Heroku Postgres
How to write a unit test for Spring Boot 2
Spring boot memo writing (1)
First Spring Boot (DI)
SPRING BOOT learning record 02
[Spring Boot] How to create a project (for beginners)
Customizer for Platform Transaction Manager added from Spring Boot 1.5
Spring Boot exception handling
Spring Boot Servlet mapping
Spring boot development-development environment-
Spring Boot learning procedure
Learning Spring Boot [Beginning]
Spring boot memo writing (2)
Spring Boot 2.2 Document Summary
[Spring Boot] DataSourceProperties $ DataSourceBeanCreationException
Spring Boot 2.3 Application Availability
Spring boot tutorials Topics
Download with Spring Boot
Change the injection target for each environment with Spring Boot 2
Introductory hands-on for beginners of Spring 5 & Spring Boot 2 has been released
I haven't understood after touching Spring Boot for a month
Introducing Spring Boot2, a Java framework for web development (for beginners)
Various switching application.properties for each environment when Spring Boot starts
[Java] Sample project for developing web applications with Spring Boot
[Spring Boot] Environment construction (macOS)
Try Spring Boot from 0 to 100.
Generate barcode with Spring Boot
Hello World with Spring Boot
Spring Boot on Microsoft Azure
Implement GraphQL with Spring Boot
Spring Boot tutorial task schedule
Spring 5 & Spring Boot 2 Hands-on preparation procedure
Get started with Spring boot
Spring Boot 2 multi-project in Gradle
[Spring Boot] Web application creation
spring boot port duplication problem
Run LIFF with Spring Boot
SNS login with Spring Boot
Spring Boot Hot Swapping settings
Introduction to Spring Boot ① ~ DI ~
File upload with Spring Boot
Spring Boot starting with copy
Introduction to Spring Boot ② ~ AOP ~
CICS-Run Java application-(4) Spring Boot application
Spring Boot starting with Docker