package com.example.demo; import bean.Employee; import dao.EmployeeDao; import org.junit.jupiter.api.Test; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.math.BigDecimal; @MapperScan("da0") @SpringBootTest public class text { @Autowired EmployeeDao employeeDao; @Test void test(){ Employee employee = employeeDao.getEmpById(1); System.out.println("employee id:"+employee.getId()); Employee employee1=new Employee(); employee1.setId(1); employee1.setName("test"); employee1.setAge(30); employee1.setGender("男"); employee1.setAddress("安徽"); employee1.setSalary(new BigDecimal("100")); employeeDao.addEmp(employee1); System.out.println("添加成功"); } }
时间: 2025-06-23 14:18:47 浏览: 17
<think>好的,我现在需要帮助用户展示如何在Spring Boot项目中进行MyBatis的单元测试,特别是使用@Autowired注入EmployeeDao并执行增删改查操作。首先,我得回想一下Spring Boot和MyBatis整合的基本配置,以及单元测试的常规做法。
用户提到要使用@Autowired注入EmployeeDao,这说明他们可能已经配置了MyBatis的Mapper扫描,确保接口能被正确识别。接下来,单元测试需要用到Spring Boot的测试支持,比如@SpringBootTest注解,这能启动应用的上下文,方便依赖注入。
然后,我需要考虑测试类的结构。测试类应该放在src/test/java下,并且使用@SpringBootTest来注解,这样Spring会加载应用程序的配置。用户可能还需要在测试类中自动注入EmployeeDao,所以需要用@Autowired注解。
接下来是具体的测试方法。每个CRUD操作都需要单独的测试方法,比如testInsertEmployee、testSelectEmployee等。对于插入操作,可能需要先插入一条记录,然后查询验证是否存在。但要注意测试的独立性,每个测试方法执行后不应该影响其他测试,所以可能需要使用事务回滚,比如添加@Transactional和@TestRollback注解,这样测试后的数据不会污染数据库。
另外,测试数据库的配置可能需要使用内存数据库,比如H2,这样可以提高测试速度并隔离环境。用户需要在application.properties或application-test.properties中配置测试用的数据源。
我还需要确保MyBatis的Mapper接口被正确扫描,通常是通过在启动类添加@MapperScan注解,或者在每个Mapper接口上使用@Mapper注解。这样Spring才能创建接口的代理实现,并注入到测试类中。
可能还需要考虑事务管理,确保每个测试方法在事务中执行,并在完成后回滚。这可以通过在测试类或方法上添加@Transactional和@Rollback来实现。不过,用户可能需要根据实际情况调整,比如某些测试需要提交事务来验证持久化效果。
最后,示例代码应该包括测试类的结构、依赖注入、测试方法的具体实现,以及必要的注解说明。同时,要提醒用户注意配置文件和依赖的正确性,比如pom.xml或build.gradle中需要包含Spring Boot Test、MyBatis Spring Boot Starter、H2数据库等依赖。
可能遇到的问题包括依赖注入失败,这时需要检查Mapper扫描配置;数据库连接问题,需要确认测试配置文件是否正确;以及事务回滚是否生效,需要确保相关注解被正确使用。此外,测试数据初始化和清理也是需要考虑的,可以使用@Sql注解来预先执行SQL脚本。
总结步骤:配置测试类,注入Dao,编写测试方法,处理事务,配置测试数据库,确保依赖和注解正确。然后提供示例代码,并解释各部分的作用。同时,生成相关问题,帮助用户进一步学习。</think>以下是Spring Boot项目中MyBatis单元测试的完整实现示例,包含`@Autowired`注入`EmployeeDao`及CRUD操作测试:
---
### 1. 测试类配置
```java
@SpringBootTest
@Transactional // 测试后自动回滚事务
@TestExecutionListeners({
DependencyInjectionTestExecutionListener.class,
TransactionalTestExecutionListener.class
})
class EmployeeDaoTest {
@Autowired
private EmployeeDao employeeDao;
private Employee testEmployee;
@BeforeEach
void setup() {
testEmployee = new Employee();
testEmployee.setName("John Doe");
testEmployee.setEmail("[email protected]");
testEmployee.setDepartmentId(1);
}
}
```
---
### 2. CRUD操作测试方法
#### 2.1 插入测试
```java
@Test
@Rollback(true) // 确保回滚
void testInsertEmployee() {
int result = employeeDao.insert(testEmployee);
assertEquals(1, result);
assertNotNull(testEmployee.getId()); // 验证自增ID
}
```
#### 2.2 查询测试
```java
@Test
void testSelectEmployee() {
employeeDao.insert(testEmployee);
Employee found = employeeDao.selectById(testEmployee.getId());
assertEquals("[email protected]", found.getEmail());
}
```
#### 2.3 更新测试
```java
@Test
void testUpdateEmployee() {
employeeDao.insert(testEmployee);
testEmployee.setName("Jane Doe");
int result = employeeDao.update(testEmployee);
assertEquals(1, result);
}
```
#### 2.4 删除测试
```java
@Test
void testDeleteEmployee() {
employeeDao.insert(testEmployee);
int result = employeeDao.delete(testEmployee.getId());
assertEquals(1, result);
}
```
---
### 3. 配置文件示例 (`src/test/resources/application-test.properties`)
```properties
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.sql.init.mode=always
```
---
### 4. 关键配置说明
1. **依赖注入**:通过`@SpringBootTest`加载Spring上下文,`@Autowired`自动注入DAO接口[^2]
2. **事务控制**:`@Transactional`与`@Rollback`配合确保测试数据不污染数据库
3. **测试数据库**:使用H2内存数据库加速测试执行
4. **MyBatis集成**:需确保主配置包含`@MapperScan("com.example.dao")`[^4]
---
### 5. Maven依赖参考 (pom.xml)
```xml
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
```
---
阅读全文
相关推荐








<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>员工信息</title>
<script type="text/javascript" th:src="@{/js/vue.global.js}"></script>
</head>
<body>
员工信息
编号
姓名
邮箱
性别
操作
删除
修改
<form id="deleteForm" method="post">
<input type="hidden" name="_method" value="delete">
</form>
<script type="text/javascript">
var vue = new Vue({
el: "#dataTable",
methods: {
deleteEmployee: function (event) {
var deleteForm = document.getElementById("deleteForm");
deleteForm.action = event.target.href;
deleteForm.submit();
event.preventDefault();
}
}
});
</script>
</body>
</html> //删除员工信息
@RequestMapping(value = "/employee/{id}",method = RequestMethod.DELETE)
public String deleteEmployee(@PathVariable("id") Integer id){
employeeDao.delete(id);
return "redirect:/employee";
} <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
encoding
UTF-8
</init-param>
<init-param>
forceResponseEncoding
true
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>hiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
contextConfigLocation
classpath:springMVC.xml
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app> <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.atguigu.rest"/>
<bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
<bean class="org.thymeleaf.spring5.SpringTemplateEngine">
<bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
</bean>
</bean>
</bean>
<mvc:view-controller path="/" view-name="index"></mvc:view-controller>
<mvc:default-servlet-handler></mvc:default-servlet-handler>
<mvc:annotation-driven></mvc:annotation-driven>
</beans> 报错 405 找不到方法




