In construction.
Spring test annotations:
@SpringBooTest
@DataJpaTest
@TestPropertySource
@ActiveProfiles
@Sql
@SpringBootTest
It is used for an integration test and loading the entire application context. Through the attribute classes, you may specify the classes and narrow down the scope of the application context. There is another important attribute, webEnviornment, which may specify the type of web application context and also we may turn it off for some tests which do need a web context, so as to lighten the test.
@TestPropertySource
In some cases, we may need specific properties for a test, by overriding the properties defined in the src resources or by adding new properties. You have two ways to specify test-specific properties. @TestPropertySource is applied at the class level, and loading a property file for the current test from the classpath by default, or from a specific location. Rather than loading a test property file, using @ActiveProfiles("test") to activate a specific profile, it may bring in a profile-specific property. meanwhile, It offers an inline way to set properties, to set property-value pairs.
@SpringBootTest
@TestPropertySource("classpath:mytest-application.properties")
@Slf4j
class LinearRegressionApplicationTests {
@Value("${my.math}")
private boolean myMath;
@DataJpaTest
It is an annotation that tailors the application context enough to test a repository. All beans above the repository will not be created, but only relevant ones for the current test.
A feature of @DataJpaTest, it activates an embedded database and disabling other data sources. In this case, if your project by default is using a real database, then you need to disable auto-configuring embedded database
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@ActiveProfiles("dev") only trigger the bean data-source active. this is why application-dev.properties are not activated by @ActiveProfiles("dev").
Configuring Spring boot test with different Data Source
When a Spring boot project has multiple data-source, @DataJpaTest may fall in an error, loading application-Context failure.
@Sql
@DataJpaTest
@Sql("classpath:insert-data.sql")
@Sql(scripts = {"classpath:delete-test-data.sql"}, executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
class PersonRepoTest {
@Autowired
private PersonRepo personRepo;
@SqlMergeMode
@SqlConfig
configure different data-source for test
@ContextConfiguration
@ContextConfiguration loads an ApplicationContext for Spring integration test. @ContextConfiguration can load ApplicationContext using XML resource or the JavaConfig annotated with @Configuration. The @ContextConfiguration annotation can also load a component annotated with @Component, @Service, @Repository etc.
No comments:
Post a Comment