我是junit的新手,我有一个存储库,如下所示:
@Repository
public interface ChartRepository extends JpaRepository<Chart, Integer>{
}
和我的图表实体类如下:
@Entity
@Table(name = "Chart")
public class Chart {
@Column(name = "ENT_ID")
private String entID;
@Column(name = "ent_NAME")
private String entName;
@Column(name = "ent_PRODUCER_ID")
private String entProducerId;
@Id
@Column(name = "ent_Rc_ID")
@SequenceGenerator(name = "ent_RC_ID_SEQ", sequenceName="ent_RC_ID_SEQ", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ent_RC_ID_SEQ")
private Integer entReceiveId;
@Column(name = "JOB_ID")
private Integer jobId;
@Column(name = "CREATE_DT")
private Timestamp createdDate;
//getters and Setters
}
现在,我们能否为存储库类编写测试用例。如果是这样我们怎么能这样做。任何人都可以建议我一些代码示例。
答案 0 :(得分:0)
您可以在其中创建@DataJpaTest
和@Autowire
您的存储库。例如:
@RunWith(SpringRunner.class)
@DataJpaTest
public class MyJpaTest {
@Autowired
private ChartRepository chartRepository;
@Test
public void myTest() {
...
}
}
答案 1 :(得分:0)
我强烈建议使用任何内存数据库来测试JPA存储库,不要使用模拟测试框架,如Mockito,EasyMock等。在Dao层中,不应该有任何业务逻辑来模拟。它应该是简单的读/写操作。
我为此使用h2database。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
classes = {DatabaseConfig.class},
loader = AnnotationConfigContextLoader.class)
public class ChartRepositoryTest {
@Autowired
private ChartRepository cartRepository;
@Test
public void testfind() {
// do find , insert and validate the response
}
}
testCompile('com.h2database:h2:1.4.196')
这是数据库配置文件看起来像
@Configuration
@EnableJpaRepositories(basePackages = "com.mypackage.repository")
@PropertySource("application-test.properties")
@EnableTransactionManagement
public class DatabaseConfig {
@Autowired
private Environment env;
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.user"));
dataSource.setPassword(env.getProperty("jdbc.pass"));
return dataSource;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "com.mypackage.v2" });
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "create");
properties.setProperty("hibernate.dialect","org.hibernate.dialect.H2Dialect");
return properties;
}
}