1. 程式人生 > >Spring的單元測試

Spring的單元測試

   一、在已經通過逆向工程生成相應類、介面、mapper後,希望向類中注入屬性並新增自己的方法

(1)向類中注入屬性: private Department department;

        向員工類中注入部門的屬性,並生成get、set方法

(2)修改mapper介面,新增新的方法:    

 List<Employee> selectByExampleWithDept(EmployeeExample example);
    
    Employee selectByPrimaryKeyWithDept(Integer empId); 

(3)修改配置檔案

 <resultMap type="com.atguigu.crud.bean.Employee" id="WithDeptResultMap">
  	<id column="emp_id" jdbcType="INTEGER" property="empId" />
    <result column="emp_name" jdbcType="VARCHAR" property="empName" />
    <result column="gender" jdbcType="CHAR" property="gender" />
    <result column="email" jdbcType="VARCHAR" property="email" />
    <result column="d_id" jdbcType="INTEGER" property="dId" />
    <!-- 指定聯合查詢出的部門欄位的封裝 -->
    <association property="department" javaType="com.atguigu.crud.bean.Department">
    	<id column="dept_id" property="deptId"/>
    	<result column="dept_name" property="deptName"/>
    </association>
  </resultMap>
 <sql id="WithDept_Column_List">
  	e.emp_id, e.emp_name, e.gender, e.email, e.d_id,d.dept_id,d.dept_name
  </sql>
  <!--   List<Employee> selectByExampleWithDept(EmployeeExample example);
    Employee selectByPrimaryKeyWithDept(Integer empId); 
    -->
   <!-- 查詢員工同時帶部門資訊 -->
  <select id="selectByExampleWithDept" resultMap="WithDeptResultMap">
	   select
	    <if test="distinct">
	      distinct
	    </if>
	    <include refid="WithDept_Column_List" />
		FROM tbl_emp e
		left join tbl_dept d on e.`d_id`=d.`dept_id`
	    <if test="_parameter != null">
	      <include refid="Example_Where_Clause" />
	    </if>
	    <if test="orderByClause != null">
	      order by ${orderByClause}
	    </if>
  </select>
  <select id="selectByPrimaryKeyWithDept" resultMap="WithDeptResultMap">
   	select 
    <include refid="WithDept_Column_List" />
    FROM tbl_emp e
	left join tbl_dept d on e.`d_id`=d.`dept_id`
    where emp_id = #{empId,jdbcType=INTEGER}
  </select>

二、使用Spring的單元測試

 推薦Spring的專案就可以使用Spring的單元測試,可以自動注入我們需要的元件
 * 1.匯入Spring Test模組
 * [email protected]指定配置檔案的位置
 * [email protected](SpringJUnit4ClassRunner.class)

 * 4.直接@Autowired要使用的元件即可

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring/applicationContext-*.xml"})
public class MapperTest {
	
	@Autowired
	DepartmentMapper departmentMapper;
	
	/**
	 * 測試DepartmentMapper
	 * 
	 */
	@Test
	public void testCRUD(){
		System.out.println(departmentMapper);
	}
}

控制檯出現以下情況說明測試成功,或者單元測試結果顯示綠色條


注意:使用逆向工程時,一定不要多次點,否則會出問題的!!!!!!!!