1.Mapper层(DAO层)单测
- 该mapper层主要用于测试编写的SQL是否存在问题,测试数据不经过数据库,不会对现存的表数据造成影响。
- 优点:测试数据不走本地数据库的表,不会对表中的数据造成影响。
- 缺点:测试配置的文件比较繁琐,需要花费一定的时间成本。
本例使用的是在XxxMapper.xml中写SQL,开发工具为IDE,maven工程(以comment为例)。
- 目录结构
- schema-init.sql
说明:该文件中存放的是要测试的数据库表结构(待会测试走的就是这个表,而不是我们当前使用的mysql或者Oracle里面的表)
- comment-delete-setupData.xml
说明:随便造数据即可,但日期类型需要特别注意,其他类型默认赋值为字符串类型;其他xxx.xml类似
- 测试类(重点)
说明:commentMapperTest.java全部代码如下,我们会注意到有setUpData和expectedData之分,前者是我们操作的数据,后者是我们操作之后希望变成的数据,通过这样的判断就可以知道SQL是否有错
import com.github.springtestdbunit.annotation.DatabaseSetup;
import com.github.springtestdbunit.annotation.ExpectedDatabase;
import com.github.springtestdbunit.assertion.DatabaseAssertionMode;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
public class CommentMapperTest extends BaseOrmTest {
protected static Logger logger = LoggerFactory.getLogger(CommentMapperTest.class);
@Autowired
private CommentMapper commentMapper;
@Test
@ExpectedDatabase(table = "sns_co