Eclipse Maven:如何使用Spring配置文件运行测试

13
我想使用不同的配置文件运行Maven,但貌似没有起作用。我为我的JPAConfiguration创建了两个不同的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运行我的单元测试时,一切都正常。如果我将测试类中的配置文件从dev移动到test,然后再从test移动到dev,也能正常工作。我的意思是测试通过,并显示“使用dev”或“使用test”的消息。

我想使用maven(带有m2e)运行测试,并创建了以下配置:

Eclipse-Maven-Configuration

但无论我如何更改配置文件,测试始终在启动。我试图从Maven -> 选择Maven配置文件激活配置文件,但结果相同。我错过了什么,但我不知道是什么。我不明白。你能帮我吗?

谢谢

2个回答

33
根据您的配置@ActiveProfiles,在测试执行期间将激活两个配置文件。如果您想通过Maven控制测试用例的活动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测试。属性值将自动激活相应的配置文件。

或者

在执行时通过maven参数将其传递给surefire插件,例如:

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


非常感谢您的帮助。 目前我并不使用maven命令行,而是使用eclipse。因此我不直接运行lvn命令,而是使用m2e。但它并不能完全适用于所有解决方案: 1)我在JUnit测试中删除了@ActiveProfile,并在Eclipse运行配置环境中添加了spring.profiles.active(dev)。 (它可以工作) 2)我通过在设置中添加属性spring.profiles.active来更新pom.xml,它可以工作。 3)我使用dev、test和surfire插件配置了配置文件,并删除了设置属性,但当我在环境中运行maven时,它不使用定义的参数。 - Jonathan Lebrun
最后,我需要在每个Maven配置中定义spring.profiles.active。虽然它能够工作,但并不完全符合我的期望。非常感谢。 - Jonathan Lebrun

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接