已经是最新一篇文章了!
已经是最后一篇文章了!
单元测试Junit
何日请缨提锐旅,一鞭直渡清河洛。
Spring对Junit支持
- 添加依赖
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
- Junit4
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MyConfig.class)
public class SpringJunit4Test {
...
}
- Junit5
@ContextConfiguration(classes = MyConfig.class)
@ExtendWith(SpringExtension.class)
public class SpringJunit5Test {
...
}
what’s your problem
单元测试启动问题
测试代码(application.yml数据库配置已完成):
@SpringBootTest
@MapperScan("com.pika.mapper")
public class MyTest {
@Resource
private UserMapper userMapper;
@Test
public void test1() {
User user = userMapper.selectById(3);
System.out.println("user = " + user);
}
}
出错:
java.lang.IllegalStateException:Unable to find a@SpringBootConfiguration,you need to use@ContextConfiguration or@SpringBootTest(classes =...) with your test
排查:
@SpringBootTest(classes = MyTest.class)
@MapperScan("com.pika.mapper")
public class MyTest {
@Resource
private UserMapper userMapper;
@Test
public void test1() {
User user = userMapper.selectById(3);
System.out.println("user = " + user);
}
}
新问题
Caused by:java.lang.IllegalArgumentException:Property'sqlSessionFactory'or'sqlSessionTemplate'are required
正确的解决方式:
添加启动类
@SpringBootTest(classes = {DockerMain6001.class})
@MapperScan("com.pika.mapper")
public class MyTest {
@Resource
private UserMapper userMapper;
@Test
public void test1() {
User user = userMapper.selectById(3);
System.out.println("user = " + user);
}
}
额外的可能
原因时Mytest类与主启动类所在的包路径不一致导致找不到配置类
以上除了指明主启动类,将测试类的所在包与主启动类包名一致就可以了
package com.pika;
import com.pika.entity.User;
import com.pika.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
/**
* Desc:
*
* @since: 2022/11/18 8:49
* @author: pikachu
*/
@SpringBootTest
public class MyTest {
@Resource
private UserMapper userMapper;
@Test
public void test1() {
User user = userMapper.selectById(3);
System.out.println("user = " + user);
}
}
版权声明:如无特别声明,本站收集的文章归 HuaJi66/Others 所有。 如有侵权,请联系删除。
联系邮箱: GenshinTimeStamp@outlook.com
本文标题:《 单元测试Junit 》
本文链接:/%E5%BC%80%E5%8F%91%E7%9B%B8%E5%85%B3/%E5%B7%A5%E5%85%B7/springbootTest.html