前言
接着之前的springboot项目,来写springboot对dao层接口测试。
正文
之前我的springboot项目在初始化就自动引入了测试依赖,所以无需再次引入其他。
新增函数
mybatis自动生成了6个基本函数,但是开发中这些函数远远不够用,(新增函数写法)这里我重新增加一个函数selectAll()
得到所有的数据库记录。
- 在Mapper中新增函数
在UserMapper.java
中新增ArrayList<User> selectAll()
ArrayList<User> selectAll();
- xml映射文件中,编写函数体.
在UserMapper.xml
中新增
<select id="selectAll" resultMap="BaseResultMap">
SELECT * FROM user
</select>
- 更新services
在UserService.java
中新增
@Override
public ArrayList<User> selectAll() {
return userMapper.selectAll();
}
测试函数
在初始化已经自动生成了测试包和测试类,最简单的是在测试类直接新增代码。
- 编辑测试代码
在HellospringApplicationTests.java
代码如下
package com.nick.hello;
import com.nick.hello.dao.UserMapper;
import com.nick.hello.entity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Iterator;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
@EnableAutoConfiguration
public class HellospringApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
public void selectAllTest() {
List<User> list = userMapper.selectAll();
System.out.println(list);
Iterator iterator = list.iterator();
int i = 1;
while (iterator.hasNext()) {
User user = (User)iterator.next();
System.out.println(i + " : " + user.getId());
i++;
}
}
}
很简单,自动注入Mapper对象,然后操作对象的方法即可
2. 运行测试类
点击左侧运行标志
点击左侧的函数名可以快速找到结果