在春季测试期间如何制作CrudRepository接口的实例?
问题内容:
我有一个Spring应用程序,在其中我 不 使用xml配置,仅使用Java Config。一切正常,但是当我尝试 测试
时,在测试中启用组件自动装配时遇到了问题。因此,让我们开始吧。我有一个 界面 :
@Repository
public interface ArticleRepository extends CrudRepository<Page, Long> {
Article findByLink(String name);
void delete(Page page);
}
以及组件/服务:
@Service
public class ArticleServiceImpl implements ArticleService {
@Autowired
private ArticleRepository articleRepository;
...
}
我不想使用xml配置,因此对于我的测试,我尝试仅使用Java配置来测试ArticleServiceImpl。因此,出于测试目的,我做了:
@Configuration
@ComponentScan(basePackages = {"com.example.core", "com.example.repository"})
public class PagesTestConfiguration {
@Bean
public ArticleRepository articleRepository() {
// (1) What to return ?
}
@Bean
public ArticleServiceImpl articleServiceImpl() {
ArticleServiceImpl articleServiceImpl = new ArticleServiceImpl();
articleServiceImpl.setArticleRepository(articleRepository());
return articleServiceImpl;
}
}
在 articleServiceImpl ()我需要把实例 articleRepository
(),但它是一个接口。如何用新关键字创建新对象?是否可以不创建xml配置类并启用自动装配?在测试过程中仅使用JavaConfigurations时可以启用自动装配吗?
问题答案:
我发现这是弹簧控制器测试的最小设置,它需要自动连接的JPA存储库配置(使用带有嵌入式spring 4.1.4.RELEASE的spring-boot
1.2和DbUnit 2.4.8)。
该测试针对嵌入式HSQL DB运行,该数据库在测试开始时由xml数据文件自动填充。
测试类:
@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration( classes = { TestController.class,
RepoFactory4Test.class } )
@TestExecutionListeners( { DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
TransactionDbUnitTestExecutionListener.class } )
@DatabaseSetup( "classpath:FillTestData.xml" )
@DatabaseTearDown( "classpath:DbClean.xml" )
public class ControllerWithRepositoryTest
{
@Autowired
private TestController myClassUnderTest;
@Test
public void test()
{
Iterable<EUser> list = myClassUnderTest.findAll();
if ( list == null || !list.iterator().hasNext() )
{
Assert.fail( "No users found" );
}
else
{
for ( EUser eUser : list )
{
System.out.println( "Found user: " + eUser );
}
}
}
@Component
static class TestController
{
@Autowired
private UserRepository myUserRepo;
/**
* @return
*/
public Iterable<EUser> findAll()
{
return myUserRepo.findAll();
}
}
}
笔记:
-
@ContextConfiguration批注仅包含嵌入式TestController和JPA配置类RepoFactory4Test。
-
需要@TestExecutionListeners批注,以便后续批注@DatabaseSetup和@DatabaseTearDown生效
引用的配置类:
@Configuration
@EnableJpaRepositories( basePackageClasses = UserRepository.class )
public class RepoFactory4Test
{
@Bean
public DataSource dataSource()
{
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
return builder.setType( EmbeddedDatabaseType.HSQL ).build();
}
@Bean
public EntityManagerFactory entityManagerFactory()
{
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl( true );
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter( vendorAdapter );
factory.setPackagesToScan( EUser.class.getPackage().getName() );
factory.setDataSource( dataSource() );
factory.afterPropertiesSet();
return factory.getObject();
}
@Bean
public PlatformTransactionManager transactionManager()
{
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory( entityManagerFactory() );
return txManager;
}
}
UserRepository是一个简单的界面:
public interface UserRepository extends CrudRepository<EUser, Long>
{
}
EUser是一个简单的@Entity注释类:
@Entity
@Table(name = "user")
public class EUser
{
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
@Max( value=Integer.MAX_VALUE )
private Long myId;
@Column(name = "email")
@Size(max=64)
@NotNull
private String myEmail;
...
}
FillTestData.xml:
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
<user id="1"
email="alice@test.org"
...
/>
</dataset>
DbClean.xml:
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
<user />
</dataset>