It feels natural to write tests on a project when I’m new to SpringBoot. I haven’t tried to build an integrated test environment by myself, haven’t paid attention to what packages I need to introduce to write tests, and just follow what others write. After the project, I tried to write a demo and corresponding tests. This article is my own tram pit diary, no guidance, use DBUNIT integration test, error, please bear more, welcome to correct ~!
1. Test environment
testImplementation("Org. Dbunit: dbunit: 2.5.2.")
testImplementation("Com. Making. Springtestdbunit: spring - test - dbunit: 1.3.0")
testImplementation 'org.springframework.boot:spring-boot-starter-test'
Copy the code
DEUNIT official handbook: springtestdbunit. Making. IO/spring – the test…
Code 2.
@SpringBootTest @ContextConfiguration @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DbUnitTestExecutionListener.class, DirtiesContextTestExecutionListener.class, TransactionDbUnitTestExecutionListener.class, })``` public class StudentRepositoryTest { @Autowired private StudentRepository studentRepository; @Test @DatabaseSetup("/dbunit/studentTestSample.xml") public void should_get_student_info_id() { StudentInfoDo studentInfoDo = studentRepository.findStudentById(1l); assertThat(studentInfoDo.getId()).isEqualTo(1l); assertThat(studentInfoDo.getStudentId()).isEqualTo("studentId1"); assertThat(studentInfoDo.getName()).isEqualTo("studentName1"); assertThat(studentInfoDo.getGender()).isEqualTo(GenderEnum.MALE); }}Copy the code
The XML file:
<? The XML version = "1.0" encoding = "utf-8"? > <dataset> <student_info id="1" student_id="studentId1" student_name="studentName1" age="7" gender="MALE" grouped="0" /> </dataset>Copy the code
SpringBootTest this annotation test when necessary, if is to use junit 4, should add here * * @ RunWith (SpringJUnit4ClassRunner. Class) * *, But after JUnit5 (or 5 if Jupiter is in the package) it all gets integrated into SpringBootTest
@ TestExecutionListeners official pointed out that in the manual to use DBUnit to introduce DbUnitTestExecutionListener. Class and related standard Spring listener configuration. Advice about TransactionDbUnitTestExecutionListener is the official document: This class is best introduced when you use Transactional. It causes transactions to start before databaseSetup and end after Databaseteardown.
ContextConfiguration loads the application context, which can be configured with the application to be loaded. The @autoWired interface is used to inject the corresponding REPO entity, and Spring will look up the corresponding context based on the bean. There is no need to manually configure it.
@autoWired injects the corresponding test entity
DatabaseSetup This is the annotation used by SpringDBUnit to configure the database file, Spring use # com. Making. Springtestdbunit. Dataset. FlatXmlDataSetLoader database file to read. The files in the path hold data from the database needed for ideal testing. The default is an XML file, or you can specify the desired file type reader later as you want.
The @databaseteardown annotation can be used to reset the database tables after the test is complete. As with @databasesetup, annotations can be applied at the method or class level. When using @databaseteardown, use the value and type attributes in the same way as @databasesetup.
@ExpectedDatabase(” ExpectedData.xml “) After the test is complete, the @ExpectedDatabase annotation can be used to validate the contents of the database. This annotation is typically used when tests perform inserts, updates, or deletes. Annotations can be applied to individual test methods or classes. When applied at the class level, validation occurs after each test method. Of course, you can put the store and query tests in one test method and do both at the same time, so you don’t need to write the ExpectedDatabase anymore. Meanwhile, the ExpectedDatabase has two modes: DatabaseAssertionMode. DEFAULT as any standard DbUnit test run, Perform the desired and actual data set. The complete comparison, DatabaseAssertionMode NON_STRICT will ignore but not in the expected data set to exist in the actual data table and column name. This is useful during integration tests performed against a live database containing multiple tables with multiple columns. NON_STRICT mode is recommended (there are actually more than two).
3. The problems I encountered
1.Unable to load dataset from "<filePath>" using class com.github.springtestdbunit.dataset.FlatXmlDataSetLoader] (https: / /stackoverflow.com/questions/ 70060569 /unable-to-load-dataset-from-filepath-using-class-com-github-springtestdbunit)
Copy the code
This question has bothered me for a long time. Based on the answers I found on the Internet, I tried the following methods:
- in
@DatabaseSetup
Add the classpath before the path - Add “” to each field name in the XML file
- Add version information to the XML file
- Use junit4 instead of 5
- Check that the XML file is in the path corresponding to test/resource/
- Do a github search for Spring DbUnit demo to see how other people’s demos are written, line by line
The reason for this last problem is that my XML file doesn’t have the suffix XML (I clearly remember adding the suffix and looking like XML), so I’ve been unable to find it, which is metaphysical.
When I changed the dependency and tried another method, I encountered:
2.cannot find test includes ....
Could not complete execution for Gradle Test Executor
Copy the code
Command +, call out the configuration box,
Check using IntelliJ IDEA for testing
Copy the code
Error create bean with studentJpaRepository, which is not what we want because we don’t use annotations in studentJpaRepository.
Talk about integration testing
We used @contextConfiguration to load the context, and when we want to do integration tests, we expect the project startup -> interface -> Service -> DAO layer to complete the process. This time you can use @ SpringApplicationConfiguration it will start from class loading context, and open the log, load the external properties.
. The summary
To summarize, a lot of problems are very obscure, but must be able to spend more time to solve, not whether it is to go online to search for the answer, ask questions, to making the above search the corresponding keywords to see someone else’s demo how to write, one line where is difference of contrast, problem in this way, although time consuming, but you have to believe that can solve the last, In the process of solution, guard against arrogance and impetuosity