项目学生:分片集成测试数据
這是Project Student的一部分。 其他職位包括帶有Jersey的 Web服務(wù) 客戶端,帶有Jersey的 Web服務(wù)服務(wù)器 , 業(yè)務(wù)層和帶有Spring Data的持久性 。
到目前為止,所有集成測試都使用了內(nèi)存嵌入式數(shù)據(jù)庫,該數(shù)據(jù)庫無法一次又一次地保留信息。 當(dāng)我們將REST服務(wù)器與“真實(shí)”數(shù)據(jù)庫服務(wù)器完全集成時,這種情況會發(fā)生變化-剩余的測試數(shù)據(jù)將污染我們的開發(fā)或測試數(shù)據(jù)庫。 一旦我們進(jìn)行了運(yùn)行集成測試代碼的連續(xù)集成,這將是一個非常頭疼的事情。
一種解決方案是以一種允許我們的測試使用共享開發(fā)數(shù)據(jù)庫而不污染它或其他測試的方式“分片”我們的集成測試數(shù)據(jù)。 最簡單的方法是將TestRun字段添加到所有對象。 “測試”數(shù)據(jù)將具有指示特定測試運(yùn)行的值,“實(shí)時”數(shù)據(jù)將具有空值。
確切的時間表是
TestRun表中的??任何條目將是1)主動集成測試或2)引發(fā)未處理異常的集成測試失敗(當(dāng)然,這取決于事務(wù)管理器)。 重要的是要注意,即使事務(wù)管理器執(zhí)行了回滾,我們也可以在引發(fā)意外異常后捕獲數(shù)據(jù)庫狀態(tài)-這是對junit測試運(yùn)行程序的簡單擴(kuò)展。
時間戳記和用戶字段使您可以輕松地根據(jù)其年齡(例如,超過7天的任何測試)或運(yùn)行測試的人員刪除陳舊的測試數(shù)據(jù)。
TestablePersistentObject抽象基類
此更改從持久性級別開始,因此我們應(yīng)該從持久性級別開始并逐步進(jìn)行擴(kuò)展。
我們首先用測試運(yùn)行值擴(kuò)展PersistentObject抽象基類。
@MappedSuperclass public abstract class TestablePersistentObject extends PersistentObject {private static final long serialVersionUID = 1L;private TestRun testRun;/*** Fetch testRun object. We use lazy fetching since we rarely care about the* contents of this object - we just want to ensure referential integrity to* an existing testRun object when persisting a TPO.* * @return*/@ManyToOne(fetch = FetchType.LAZY, optional = true)public TestRun getTestRun() {return testRun;}public void setTestRun(TestRun testRun) {this.testRun = testRun;}@Transientpublic boolean isTestData() {return testRun != null;} }TestRun類
TestRun類包含有關(guān)單個集成測試運(yùn)行的標(biāo)識信息。 它包含一個名稱(默認(rèn)情況下,該集成測試為classname#methodname()) ,測試的日期和時間以及運(yùn)行該測試的用戶的名稱。 捕獲其他信息將很容易。
測試對象列表為我們帶來了兩個重大勝利。 首先,如果需要(例如,在意外的異常之后),可以輕松捕獲數(shù)據(jù)庫的狀態(tài)。 其次,級聯(lián)刪除使刪除所有測試對象變得容易。
@XmlRootElement @Entity @Table(name = "test_run") @AttributeOverride(name = "id", column = @Column(name = "test_run_pkey")) public class TestRun extends PersistentObject {private static final long serialVersionUID = 1L;private String name;private Date testDate;private String user;private List<TestablePersistentObject> objects = Collections.emptyList();@Column(length = 80, unique = false, updatable = true)public String getName() {return name;}public void setName(String name) {this.name = name;}@Column(name = "test_date", nullable = false, updatable = false)@Temporal(TemporalType.TIMESTAMP)public Date getTestDate() {return testDate;}public void setTestDate(Date testDate) {this.testDate = testDate;}@Column(length = 40, unique = false, updatable = false)public String getUser() {return user;}public void setUser(String user) {this.user = user;}@OneToMany(cascade = CascadeType.ALL)public List<TestablePersistentObject> getObjects() {return objects;}public void setObjects(List<TestablePersistentObject> objects) {this.objects = objects;}/*** This is similar to standard prepersist method but we also set default* values for everything else.*/@PrePersistpublic void prepersist() {if (getCreationDate() == null) {setCreationDate(new Date());}if (getTestDate() == null) {setTestDate(new Date());}if (getUuid() == null) {setUuid(UUID.randomUUID().toString());}if (getUser() == null) {setUser(System.getProperty("user.name"));}if (name == null) {setName("test run " + getUuid());}} }TestRun類擴(kuò)展了PersistentObject,而不是TestablePersistentObject,因為我們的其他集成測試將充分利用它。
Spring數(shù)據(jù)倉庫
我們必須向每個存儲庫添加一種其他方法。
@Repository public interface CourseRepository extends JpaRepository {List<Course> findCoursesByTestRun(TestRun testRun);.... }服務(wù)介面
同樣,我們必須為每個服務(wù)添加兩個其他方法。
public interface CourseService {List<Course> findAllCourses();Course findCourseById(Integer id);Course findCourseByUuid(String uuid);Course createCourse(String name);Course updateCourse(Course course, String name);void deleteCourse(String uuid);// new method for testingCourse createCourseForTesting(String name, TestRun testRun);// new method for testingList<Course> findAllCoursesForTestRun(TestRun testRun); }我不會顯示TestRunRepository,TestRunService接口或TestRunService實(shí)現(xiàn),因為它們與我在前幾篇博客文章中所描述的相同。
服務(wù)實(shí)施
我們必須對現(xiàn)有Service實(shí)施進(jìn)行一次小的更改,并添加兩種新方法。
@Service public class CourseServiceImpl implements CourseService {@Resourceprivate TestRunService testRunService;/*** @see com.invariantproperties.sandbox.student.business.CourseService#* findAllCourses()*/@Transactional(readOnly = true)@Overridepublic List<Course> findAllCourses() {List<Course> courses = null;try {courses = courseRepository.findCoursesByTestRun(null);} catch (DataAccessException e) {if (!(e instanceof UnitTestException)) {log.info("error loading list of courses: " + e.getMessage(), e);}throw new PersistenceException("unable to get list of courses.", e);}return courses;}/*** @see com.invariantproperties.sandbox.student.business.CourseService#* findAllCoursesForTestRun(com.invariantproperties.sandbox.student.common.TestRun)*/@Transactional(readOnly = true)@Overridepublic List<Course> findAllCoursesForTestRun(TestRun testRun) {List<Course> courses = null;try {courses = courseRepository.findCoursesByTestRun(testRun);} catch (DataAccessException e) {if (!(e instanceof UnitTestException)) {log.info("error loading list of courses: " + e.getMessage(), e);}throw new PersistenceException("unable to get list of courses.", e);}return courses;}/*** @see com.invariantproperties.sandbox.student.business.CourseService#* createCourseForTesting(java.lang.String,* com.invariantproperties.sandbox.student.common.TestRun)*/@Transactional@Overridepublic Course createCourseForTesting(String name, TestRun testRun) {final Course course = new Course();course.setName(name);course.setTestUuid(testRun.getTestUuid());Course actual = null;try {actual = courseRepository.saveAndFlush(course);} catch (DataAccessException e) {if (!(e instanceof UnitTestException)) {log.info("internal error retrieving course: " + name, e);}throw new PersistenceException("unable to create course", e);}return actual;} }CourseServiceIntegrationTest
我們對集成測試進(jìn)行了一些更改。 我們只需更改一種測試方法,因為它是唯一實(shí)際創(chuàng)建測試對象的方法。 其余方法是不需要測試數(shù)據(jù)的查詢。
請注意,我們更改名稱值以確保其唯一性。 這是解決唯一性約束(例如,電子郵件地址)的一種方法。
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { BusinessApplicationContext.class, TestBusinessApplicationContext.class,TestPersistenceJpaConfig.class }) @Transactional @TransactionConfiguration(defaultRollback = true) public class CourseServiceIntegrationTest {@Resourceprivate CourseService dao;@Resourceprivate TestRunService testService;@Testpublic void testCourseLifecycle() throws Exception {final TestRun testRun = testService.createTestRun();final String name = "Calculus 101 : " + testRun.getUuid();final Course expected = new Course();expected.setName(name);assertNull(expected.getId());// create courseCourse actual = dao.createCourseForTesting(name, testRun);expected.setId(actual.getId());expected.setUuid(actual.getUuid());expected.setCreationDate(actual.getCreationDate());assertThat(expected, equalTo(actual));assertNotNull(actual.getUuid());assertNotNull(actual.getCreationDate());// get course by idactual = dao.findCourseById(expected.getId());assertThat(expected, equalTo(actual));// get course by uuidactual = dao.findCourseByUuid(expected.getUuid());assertThat(expected, equalTo(actual));// get all coursesfinal List<Course> courses = dao.findCoursesByTestRun(testRun);assertTrue(courses.contains(actual));// update courseexpected.setName("Calculus 102 : " + testRun.getUuid());actual = dao.updateCourse(actual, expected.getName());assertThat(expected, equalTo(actual));// verify testRun.getObjectsfinal List<TestablePersistentObject> objects = testRun.getObjects();assertTrue(objects.contains(actual));// delete Coursedao.deleteCourse(expected.getUuid());try {dao.findCourseByUuid(expected.getUuid());fail("exception expected");} catch (ObjectNotFoundException e) {// expected}testService.deleteTestRun(testRun.getUuid());}.... }我們可以使用@Before和@After透明地包裝所有測試方法,但是許多測試不需要測試數(shù)據(jù),而許多需要測試數(shù)據(jù)的測試則需要唯一的測試數(shù)據(jù),例如,電子郵件地址。 在后一種情況下,我們按照上述方法折疊測試UUID。
REST Web服務(wù)服務(wù)器
REST Web服務(wù)需要在請求類中添加測試uuid,并在創(chuàng)建對象時添加一些邏輯以正確處理它。
REST Web服務(wù)不支持獲取所有測試對象的列表。 “正確”的方法將是創(chuàng)建TestRun服務(wù)并響應(yīng)/ get / {id}查詢提供關(guān)聯(lián)的對象。
@XmlRootElement public class Name {private String name;private String testUuid;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getTestUuid() {return testUuid;}public void setTestUuid(String testUuid) {this.testUuid = testUuid;} }現(xiàn)在,我們可以檢查可選的testUuid字段并調(diào)用適當(dāng)?shù)腸reate方法。
@Service @Path("/course") public class CourseResource extends AbstractResource {@Resourceprivate CourseService service;@Resourceprivate TestRunService testRunService;/*** Create a Course.* * @param req* @return*/@POST@Consumes({ MediaType.APPLICATION_JSON, MediaType.TEXT_XML })@Produces({ MediaType.APPLICATION_JSON, MediaType.TEXT_XML })public Response createCourse(Name req) {log.debug("CourseResource: createCourse()");final String name = req.getName();if ((name == null) || name.isEmpty()) {return Response.status(Status.BAD_REQUEST).entity("'name' is required'").build();}Response response = null;try {Course course = null;if (req.getTestUuid() != null) {TestRun testRun = testRunService.findTestRunByUuid(req.getTestUuid());if (testRun != null) {course = service.createCourseForTesting(name, testRun);} else {response = Response.status(Status.BAD_REQUEST).entity("unknown test UUID").build();}} else {course = service.createCourse(name);}if (course == null) {response = Response.status(Status.INTERNAL_SERVER_ERROR).build();} else {response = Response.created(URI.create(course.getUuid())).entity(scrubCourse(course)).build();}} catch (Exception e) {if (!(e instanceof UnitTestException)) {log.info("unhandled exception", e);}response = Response.status(Status.INTERNAL_SERVER_ERROR).build();}return response;}.... }REST Web服務(wù)客戶端
最后,REST服務(wù)器必須添加一種其他方法。 客戶端尚不支持獲取所有測試對象的列表。
public interface CourseRestClient {/*** Create specific course for testing.* * @param name* @param testRun*/Course createCourseForTesting(String name, TestRun testRun);.... }和
public class CourseRestClientImpl extends AbstractRestClientImpl implements CourseRestClient {/*** Create JSON string.* * @param name* @return*/String createJson(final String name, final TestRun testRun) {return String.format("{ \"name\": \"%s\", \"testUuid\": \"%s\" }", name, testRun.getTestUuid());}/*** @see com.invariantproperties.sandbox.student.webservice.client.CourseRestClient#createCourse(java.lang.String)*/@Overridepublic Course createCourseForTesting(final String name, final TestRun testRun) {if (name == null || name.isEmpty()) {throw new IllegalArgumentException("'name' is required");}if (testRun == null || testRun.getTestUuid() == null || testRun.getTestUuid().isEmpty()) {throw new IllegalArgumentException("'testRun' is required");}return createObject(createJson(name, testRun));}.... }源代碼
可從http://code.google.com/p/invariant-properties-blog/source/browse/student獲取源代碼。
澄清度
我認(rèn)為在TestRun中不可能有@OneToMany到TestablePersistentObject,但是使用H2的集成測試成功了。 不幸的是,當(dāng)我使用PostgreSQL數(shù)據(jù)庫啟動完全集成的Web服務(wù)時,這會引起問題。 我將代碼留在上面,因為即使我們沒有通用集合,也總是可以有一個教室列表,一個課程列表等。 但是,代碼已從源代碼控制的版本中刪除。
更正
接口方法應(yīng)該是findCourseByTestRun_Uuid() ,而不是findCourseByTestRun() 。 另一種方法是使用JPA標(biāo)準(zhǔn)查詢–請參閱“ 項目學(xué)生:JPA標(biāo)準(zhǔn)查詢” 。
翻譯自: https://www.javacodegeeks.com/2014/01/project-student-sharding-integration-test-data.html
總結(jié)
以上是生活随笔為你收集整理的项目学生:分片集成测试数据的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用junit-drools进行JBos
- 下一篇: 施工员证备案怎么自己退出(施工员证备案)