The path to continuous integration-unit test on the data access layer (continued)

Source: Internet
Author: User
In the previous article, the configuration of the test data source was completed. Next we will continue to build a runable test.

3. Use dbunit to manage data

Maintenance of tests has always been a headache for me. I hope there will be a more easy-to-maintain and reusable way to manage the data. Select dbunit for the moment before there is a better method. (Reflection: In fact, I have been worried about nothing that has not happened, so that nothing has progressed. Starting from the existing and simplest aspects is the correct processing method.)

Introduce the dbunit and springtestdbunit packages in POM. xml. The latter provides the following annotations to use dbunit:

        <dependency>            <groupId>org.dbunit</groupId>            <artifactId>dbunit</artifactId>            <version>2.4.9</version>            <scope>test</scope>        </dependency>        <dependency>            <groupId>com.github.springtestdbunit</groupId>            <artifactId>spring-test-dbunit</artifactId>            <version>1.0.1</version>            <scope>test</scope>        </dependency>

Dbunit uses XML files to manage datasets. Using a third-party library, you can easily support JSON format. XML is used here:

<?xml version="1.0" encoding="utf-8"?><dataset>    <building id="1" name="SOHO"/>    <building id="2" name="New Gate Plaza"/>    <floor id="1" floor_num="2" building="1"/>    <floor id="2" floor_num="3" building="1"/>    <floor id="3" floor_num="5" building="2"/></dataset>

The data file is stored in/src/test/resources/, which is in the same directory as the test case. To facilitate differentiation, I used the DAO class name-tested method name-dataset. XML naming method, for example: UserDao-findByname-dataxml.set. In the future, if the test case needs to be modified, you can easily find the corresponding dataset Based on the name, without affecting other test cases.

Note:

1. The Element and Its Attribute names must correspond to the database structure one by one, rather than the entity class.

2. If the number of fields to be initialized is different for the same data object initialization, for example, eight fields to be initialized for one data object, and four fields to be initialized for the other data object. Therefore, you must put a large number of fields in front.

4. compile test cases

Check the tested code before writing the case. Two entity classes used:

package com.noyaxe.myapp.entity;import javax.persistence.Entity;import javax.persistence.Table;@Entity@Table(name = "building")public class Building extends IdEntity {    private String name;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }}

package com.noyaxe.myapp.entity;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.JoinColumn;import javax.persistence.ManyToOne;import javax.persistence.Table;@Entity@Table(name = "floor")public class Floor extends IdEntity {    private Integer floorNum;    private Building building;    @Column(name = "floor_num")    public Integer getFloorNum() {        return floorNum;    }    public void setFloorNum(Integer floorNum) {        this.floorNum = floorNum;    }    @ManyToOne(optional = false)    @JoinColumn(name = "building")    public Building getBuilding() {        return building;    }    public void setBuilding(Building building) {        this.building = building;    }}

Tested floordao:

package com.noyaxe.myapp.repository;import com.noyaxe.myapp.entity.Floor;import org.springframework.data.jpa.repository.JpaSpecificationExecutor;import org.springframework.data.repository.PagingAndSortingRepository;import java.util.List;public interface FloorDao extends JpaSpecificationExecutor<Floor>, PagingAndSortingRepository<Floor, Long> {    public Floor findByBuildingNameAndFloorNum(String building, Integer floorNum);    public List<Floor> findByBuildingName(String building);}

The test cases are also very simple:

Package COM. noyaxe. myApp. repository; import COM. gitHub. springtestdbunit. annotation. databasesetup; import COM. noyaxe. myApp. entity. floor; import Org. JUnit. test; import Org. springframework. beans. factory. annotation. autowired; import Org. springframework. test. context. junit4.springjunit4classrunner; import Org. springframework. test. context. support. dependencyinjectiontestexecutionlistener; import Org. springframework. test. context. support. dirtiescontexttestexecutionlistener; import Java. util. list; import static JUnit. framework. assert. assertnull; import static Org. JUnit. assert. assertequals; import static Org. JUnit. assert. assertnotnull; @ runwith (springjunit4classrunner. class) @ contextconfiguration ("classpath: applicationContext-test.xml") @ testexecutionlisteners ({dependencyinjectiontestexecutionlistener. class, dirtiescontexttestexecutionlistener. class, transactiondbunittestexecutionlistener. class}) public class floordaotest {@ autowired private floordao; @ Test
    @DatabaseSetup("FloorDao-findbByBuidlingName-dataset.xml")

Public void testfindbybuildingname () {list <floor> singlefloorlist = floordao. findbybuildingname ("Soho"); assertequals (1, singlefloorlist. size (); List <floor> twofloorlist = floordao. findbybuildingname ("New Gate Plaza"); assertequals (2, twofloorlist. size (); List <floor> emptyfloorlist = floordao. findbybuildingname ("test"); assertequals (0, emptyfloorlist. size () ;}@ Test

    @DatabaseSetup("FloorDao-findbByBuidlingNameAndFloorNum-dataset.xml")

Public void testfindbybuildingnameandfloornum () {floor = floordao. findbybuildingnameandfloornum ("Soho", 2); assertnotnull (floor); floor empty = floordao. findbybuildingnameandfloornum ("New Gate Plaza", 7); assertnull (empty); empty = floordao. findbybuildingnameandfloornum ("No building", 7); assertnull (empty) ;}} The Code clearly shows that the test data is introduced through databasesetup. Here we will introduce different files before each test method. If all methods can be included in one file, we can also use databasesetup to introduce data files before the class.

So far, a complete data-layer test case has been presented and can be run. However, the actual process is not so smooth. The following article will summarize the problems encountered.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.