本文内容基于【Spring整合MyBatis】Spring整合MyBatis的具体方法进行测试
文章目录 1. 导入相关坐标2. 使用Junit测试所需注解3. 在测试类中写相关内容 1. 导入相关坐标在pom.xml中导入相关坐标:
<dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13.2</version><scope>test</scope></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.3.25</version></dependency> 2. 使用Junit测试所需注解一般测试Service类,我们在test包下建立测试类,并使用@Runwith来指定运行期,通过@ContextConfiguration来指定配置类
package com.example.project2.service;import com.example.project2.config.SpringConfig;import org.junit.runner.RunWith;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes = SpringConfig.class)public class AccountServiceTest {}关于@Runwith找了两篇博客:
Junit的基础讲解一Junit的基础讲解二 3. 在测试类中写相关内容使用依赖注入在这里注入accountService,在测试方法中上需要加上@Test的注解
package com.example.project2.service;import com.example.project2.config.SpringConfig;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes = SpringConfig.class)public class AccountServiceTest {@Autowiredprivate AccountService accountService;@Testpublic void testFIndById(){System.out.println(accountService.findById(1));}}运行结果: 将findById()中的id改成2,运行结果: