java - eclipse maven : run test with spring profile

标签 java spring maven m2eclipse m2e

我想用不同的配置文件运行 Maven,但它似乎不起作用。 我为我的 JPAConfiguration 创建了 2 个不同的 java 类:

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(); 
    } 

} 

在我的 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> 

最后,我有一个测试类:

@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"); 
    } 
} 

当我从 Eclipse 运行我的单元测试时,它工作正常。如果我将测试类中的配置文件从开发移动到测试,再从测试移动到开发,它就可以工作。我的意思是测试通过并且显示消息“使用开发”或“使用测试”。

我想从 maven(使用 m2e)运行测试并且我创建了这个配置:

Eclipse-Maven-Configuration

但是当我更改配置文件时,测试总是开始。

我尝试从 Maven 激活配置文件 -> 选择 Maven 配置文件,但结果相同。

我错过了什么,但我不知道是什么。我不明白。

你能帮帮我吗?

谢谢

最佳答案

根据您的配置@ActiveProfiles,这两个配置文件都将在您的测试执行期间被激活。如果您想通过 Maven 控制测试用例的 Activity spring 配置文件,那么我建议您从测试类中删除 @ActiveProfiles 注释并将 spring.profiles.active 指定为系统属性。您可以使用以下任一方式进行操作:

在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>

您可以通过传递不带配置文件名称的 spring.profiles.active 参数来简单地运行 maven 测试。配置文件将使用属性 spring.profiles.active 的值自动激活

执行时通过maven参数传给surefire插件,如:

mvn -DargLine="-Dspring.profiles.active=dev"

关于java - eclipse maven : run test with spring profile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38811196/

相关文章:

java - 将 Maven 依赖项添加到我的 Maven 项目时找不到资源

java - IntelliJ idea 图形用户界面设计器 + maven

java - 更改 Android Studio 中的菜单图标

java - Riak/Java - 使用 AND 条件和排序对二级索引进行 MapReduce 查询的最佳实践

JAVA ObjectNode 获取为空

java - 使用 spring-data-redis 更新 redis 中的实体

java - 如何对依赖于 Maven 本地存储库的 Java 应用程序进行 Docker 化?

java - 有没有办法将 ExpandableListView 嵌套在relativelayout 中?

java - 将 ListView 内的产品价格总和计算为字符串

使用 JBoss/Spring 和 NetBeans 部署 WebAppp 时出现 javax.naming.NameNotFoundException