java Eclipse Maven:使用 spring 配置文件运行测试
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38811196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Eclipse Maven: run test with spring profile
提问by Jonathan Lebrun
I want to run maven with different profile but it seems not working. I created 2 differents java class for my JPAConfiguration :
我想用不同的配置文件运行 maven,但它似乎不起作用。我为我的 JPAConfiguration 创建了 2 个不同的 java 类:
JPAConfiguration.class and JPAConfigurationTest.class
JPAConfiguration.class 和 JPAConfigurationTest.class
@Configuration
@Profile({"dev"})
@EnableTransactionManagement(proxyTargetClass = true)
@EnableJpaRepositories(basePackages = { "com.jle.athleges.model.repository", "com.jle.athleges.security.repository" })
@ComponentScan(basePackages = { "com.jle.athleges.model.services", "com.jle.athleges.security.services" })
public class JpaConfiguration {
@Bean
public DataSource dataSource() throws SQLException {
System.out.println("use dev");
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
builder.setName("dev");
return builder.setType(EmbeddedDatabaseType.H2).build();
}
@Bean
public EntityManagerFactory entityManagerFactory() throws SQLException {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("com.jle.athleges.model.entity", "com.jle.athleges.security.entity");
factory.setDataSource(dataSource());
factory.afterPropertiesSet();
return factory.getObject();
}
@Bean
public EntityManager entityManager(EntityManagerFactory entityManagerFactory) {
return entityManagerFactory.createEntityManager();
}
@Bean
public PlatformTransactionManager transactionManager() throws SQLException {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory());
return txManager;
}
@Bean
public HibernateExceptionTranslator hibernateExceptionTranslator() {
return new HibernateExceptionTranslator();
}
}
@Configuration
@Profile({"test"})
@EnableTransactionManagement(proxyTargetClass = true)
@EnableJpaRepositories(basePackages = { "com.jle.athleges.model.repository", "com.jle.athleges.security.repository" })
@ComponentScan(basePackages = { "com.jle.athleges.model.services", "com.jle.athleges.security.services" })
public class JpaConfigurationTest {
@Bean
public DataSource dataSource() throws SQLException {
System.out.println("use test");
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
builder.setName("test");
return builder.setType(EmbeddedDatabaseType.H2).build();
}
@Bean
public EntityManagerFactory entityManagerFactory() throws SQLException {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("com.jle.athleges.model.entity", "com.jle.athleges.security.entity");
factory.setDataSource(dataSource());
factory.afterPropertiesSet();
return factory.getObject();
}
@Bean
public EntityManager entityManager(EntityManagerFactory entityManagerFactory) {
return entityManagerFactory.createEntityManager();
}
@Bean
public PlatformTransactionManager transactionManager() throws SQLException {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory());
return txManager;
}
@Bean
public HibernateExceptionTranslator hibernateExceptionTranslator() {
return new HibernateExceptionTranslator();
}
}
In my pom.xml, I have this :
在我的 pom.xml 中,我有这个:
<project>
…
<dependencies>
…
</dependencies>
<profiles>
<profile>
<id>dev</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>test</id>
</profile>
</profiles>
<build>
<finalName>AthleGes</finalName>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<debug>true</debug>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>${jetty-maven-plugin.version}</version>
<configuration>
<jettyEnvXml>src/test/resources/jetty-env.xml</jettyEnvXml>
<scanIntervalSeconds>10</scanIntervalSeconds>
<stopKey>foo</stopKey>
<stopPort>9999</stopPort>
</configuration>
<executions>
<execution>
<id>start-jetty</id>
<phase>pre-integration-test</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<scanIntervalSeconds>0</scanIntervalSeconds>
<daemon>true</daemon>
</configuration>
</execution>
<execution>
<id>stop-jetty</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
And finally, I have a test class :
最后,我有一个测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles(profiles = {"test","dev"})
@ContextConfiguration(classes = { JpaConfigurationTest.class, JpaConfiguration.class, SecurityConfig.class })
@TestExecutionListeners({
DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class,
})
public class MemberServiceImpTest {
static Logger log = LoggerFactory.getLogger(MemberServiceImpTest.class);
@Autowired
private MemberService memberService;
@Autowired
private MemberRepository repository;
@Before
public void setUp(){
repository.deleteAll();
}
@Test
public void saveMember() {
log.debug("Start saveMember");
Member a = new Member();
a.setFirstname("aaa");
a.setLastname("hhh");
a.setId(0L);
Assert.assertNotNull(memberService.save(a));
log.debug("End saveMember");
}
@Test
public void getAllMembers() {
log.debug("Start getAllMember");
long sizeBefore = repository.count();
Member a = new Member();
a.setFirstname("aaa");
a.setLastname("hhh");
a.setId(2L);
Member b = new Member();
b.setFirstname("aaa");
b.setLastname("hhh");
b.setId(1L);
memberService.save(a);
memberService.save(b);
Assert.assertEquals(memberService.getAll().size(),sizeBefore + 2);
log.debug("End getAllMember");
}
}
When I run my unit test from Eclipse, it is working fine. If I move the profile in the test class from dev to test and from test to dev, it is working. I mean the test pass and the displayed message "use dev" or "use test" is displayed.
当我从 Eclipse 运行我的单元测试时,它工作正常。如果我将测试类中的配置文件从 dev 移动到 test,从 test 移动到 dev,它就可以工作。我的意思是测试通过并显示显示的消息“使用开发”或“使用测试”。
I want to run the tests from maven (with m2e) and I created this configuration :
我想从 maven(使用 m2e)运行测试,我创建了这个配置:
But when I change the profile, test is always started.
但是当我更改配置文件时,总是会开始测试。
I tried to activate profile from Maven -> Select Maven Profile but I have been the same result.
我试图从 Maven 激活配置文件 - > 选择 Maven 配置文件,但我得到了相同的结果。
I miss something but I don't know what. I don't understand.
我想念一些东西,但我不知道是什么。我不明白。
Could you help me?
你可以帮帮我吗?
Thanks
谢谢
回答by Ajay Deshwal
As per your configuration @ActiveProfiles, both the profiles will be activated during your test execution. If you want to control the active spring profile for test cases through maven, then I would suggest you to remove @ActiveProfiles annotation from your test class and specify spring.profiles.active as a system property. You could do it using either of the following ways:
根据您的配置@ActiveProfiles,这两个配置文件都将在您的测试执行期间被激活。如果您想通过 maven 控制测试用例的活动 spring 配置文件,那么我建议您从测试类中删除 @ActiveProfiles 注释并将 spring.profiles.active 指定为系统属性。您可以使用以下任何一种方式来做到这一点:
Set it in the maven surefire plugin configurtion:
在 maven surefire 插件配置中设置它:
<project>
<properties>
<spring.profiles.active>dev</spring.profiles.active>
</properties>
<profiles>
<profile>
<id>dev</id>
<activation>
<property>
<name>spring.profiles.active</name>
<value>dev</value>
</property>
</activation>
</profile>
<profile>
<id>test</id>
<activation>
<property>
<name>spring.profiles.active</name>
<value>test</value>
</property>
</activation>
</profile>
</profiles>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>-Dspring.profiles.active=${spring.profiles.active}</argLine>
</configuration>
</plugin>
</plugins>
</build>
</project>
You can simply run maven test as you are doing already by passing spring.profiles.active parameter without the profile name. Profile will be activated automatically using value of the property spring.profiles.active
您可以通过传递没有配置文件名称的 spring.profiles.active 参数来简单地运行 maven 测试。配置文件将使用属性 spring.profiles.active 的值自动激活
OR
或者
Pass it to surefire plugin through maven parameter during execution like:
在执行过程中通过 Maven 参数将其传递给surefire插件,例如:
mvn -DargLine="-Dspring.profiles.active=dev"
mvn -DargLine="-Dspring.profiles.active=dev"
回答by Inneart
If you are running with different profiles regularly for testing purposes on Eclipse, you can select the active profile directly in Eclipse without modifying the pom.
如果为了在 Eclipse 上进行测试而定期使用不同的配置文件运行,则可以直接在 Eclipse 中选择活动配置文件,而无需修改 pom.xml 文件。
Select active profile under Maven > Select Maven Profiles...