Eclipse Maven:运行 使用 spring 配置文件进行测试

Eclipse Maven: run test with spring profile

我想 运行 具有不同配置文件的 maven,但它似乎不起作用。 我为我的 JPAConfiguration 创建了 2 个不同的 java 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(); 
    } 

} 

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

最后,我有一个测试 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"); 
    } 
} 

当我 运行 从 Eclipse 进行单元测试时,它工作正常。如果我将测试 class 中的配置文件从开发移动到测试,再从测试移动到开发,它就可以工作。我的意思是测试通过并显示显示的消息 "use dev" 或 "use test"。

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

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

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

我错过了一些东西,但我不知道是什么。我不明白。

你能帮帮我吗?

谢谢

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

您可以简单地 运行 maven 测试,就像您已经在做的那样,通过传递 spring.profiles.active 参数而不传递配置文件名称。配置文件将使用 属性 spring.profiles.active

的值自动激活

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

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

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

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