在单元测试中为@Import spring配置设置@Value属性?

时间:2015-02-02 12:54:31

标签: java spring unit-testing

如何为@Value进入单元测试的上下文设置@Import属性?

例如:

@Configuration
public void DatabaseTestsConfiguration
{
  @Value("${test.generateddl:true}")
  private boolean generateDdl;

  @Bean
  public JpaVendorAdapter jpaVendorAdapter()
  {
    HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
    hibernateJpaVendorAdapter.setShowSql( false );
    hibernateJpaVendorAdapter.setGenerateDdl( generateDdl );
    hibernateJpaVendorAdapter.setDatabase( Database.H2 );
    return hibernateJpaVendorAdapter;
  }

   // Some more @Bean's here
}

在我的单元测试中:

@Test
@ContextConfiguration
public void SomeTest extends AbstractTransactionalTestNGSpringContextTests
{

  @Configuration
  @Import(DatabaseTestsConfiguration.class)
  public static class TestConfiguration
  {
  }
}

如何在单元测试中覆盖属性test.generateddlfalse?请注意,我只想将它用于此单元测试,因此在命令行上指定一些内容是不行的。

1 个答案:

答案 0 :(得分:2)

您可能需要查看http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/context/TestPropertySource.html#properties--

春天docu的例子:

@ContextConfiguration
@TestPropertySource(properties = { "timezone = GMT", "port: 4242" })