千峰商城-springboot项目搭建-03-基于springboot单元测试
1.在beans子项目下的src - main - java - com.qfedu.fmmall.entity 下创建一个实体类 User类。
User.java:
package com.qfedu.fmmall.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class User { private int userId; private String userName; private String userRealname; private String UserImg; }
2.在mapper子项目下的src - main - java - com.qfedu.fmmall.dao下新建一个 UserDAO.java:
UserDAO.java:
package com.qfedu.fmmall.dao; import com.qfedu.fmmall.entity.User; //@Repository //@Mapper public interface UserDAO { public User queryUserByName(String name); }
在mapper - src - main - resource中新建一个mappers包,在mappers包中新建一个UserMapper.xml:
UserMapper.xml:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.qfedu.fmmall.dao.UserDAO"> <resultMap id="userMap" type="User"> <id column="user_id" property="userId"/> <result column="user_name" property="userName"/> <result column="user_realname" property="userRealname"/> <result column="user_img" property="userImg"/> </resultMap> <select id="queryUserByName" resultMap="userMap"> select user_id,user_name,user_realname,user_img from users where user_name=#{name} </select> </mapper>
3.在api子项目的 src - test - java 中新建一个dao包,其中创建UserDAORest单元测试类:
UserDAOTest.java:
package dao; import com.qfedu.fmmall.ApiApplication; import com.qfedu.fmmall.dao.UserDAO; import com.qfedu.fmmall.entity.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import javax.annotation.Resource; @RunWith(SpringRunner.class) @SpringBootTest(classes = ApiApplication.class) public class UserDAOTest { @Resource private UserDAO userDAO; @Test public void queryUserByName(){ User user = userDAO.queryUserByName("li"); System.out.println(user); } }
启动测试:
测试成功!
注:编写代码时要特别关注系统有没有自动创建一些包,导致路径出现问题。通过请教老师 @高程昕老师 成功解决了这个问题,感谢老师!
下附项目的结构: