【问题标题】:Eclipse Maven: run test with spring profileEclipse Maven:使用弹簧配置文件运行测试
【发布时间】:2016-12-13 03:58:27
【问题描述】:

我想用不同的配置文件运行 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)运行测试,我创建了这个配置:

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

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

我想念一些东西,但我不知道是什么。我不明白。

你能帮帮我吗?

谢谢

【问题讨论】:

    标签: java spring maven m2eclipse m2e


    【解决方案1】:

    根据您的配置@ActiveProfiles,这两个配置文件都将在您的测试执行期间被激活。如果您想通过 Maven 控制测试用例的活动弹簧配置文件,那么我建议您从测试类中删除 @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"

    【讨论】:

    • 非常感谢您的帮助。我并没有真正在命令中使用(现在)maven,而是使用eclipse。所以我不直接运行lvn命令,我用m2e。它不适用于所有解决方案:1)我在 JUnit Test 中删除了@ActiveProfile,并在 Eclipse 运行配置环境中添加了 spring.profiles.active (dev)。 (它有效) 2)我通过在设置中添加属性 spring.profiles.active 来更新 pom.xml 并且它有效。 3) 我使用 dev、test 和 surfire 插件配置了配置文件并删除了设置属性,但是当我在环境中运行 maven 时,它不使用定义的参数。
    • 最后,我需要在每个maven配置中定义spring.profiles.active。它正在工作,但也不是我想要的。非常感谢。
    【解决方案2】:

    如果您定期使用不同的配置文件在 Eclipse 上进行测试,您可以直接在 Eclipse 中选择活动配置文件,而无需修改 pom。

    Select active profile under Maven > Select Maven Profiles...

    【讨论】:

      猜你喜欢
      • 2021-12-27
      • 1970-01-01
      • 2012-11-02
      • 2011-11-27
      • 1970-01-01
      • 1970-01-01
      • 2021-12-12
      • 1970-01-01
      • 2014-10-14
      相关资源
      最近更新 更多