测试——@RunWith(SpringRunner.class)和@SpringBootTest注解



@RunWith(SpringRunner.class)注解:

  • 是一个测试启动器,可以加载SpringBoot测试注解

  • 让测试在Spring容器环境下执行。如测试类中无此注解,将导致service,dao等自动注入失败,比如下面这个持久层的注入:



@SpringBootTest注解:目的是加载ApplicationContext,启动spring容器。


package com.cy.store.mapper;

import com.cy.store.entity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;


@RunWith(SpringRunner.class) // @RunWith(SpringRunner.class)注解是一个测试启动器,可以加载Springboot测试注解
@SpringBootTest //目的是加载ApplicationContext,启动spring容器。
public class UserMapperTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void addUserTest(){

        User user1=new User();
        user1.setUsername("用户1");
        user1.setPassword("123456");
        int i = userMapper.addUser(user1);
        System.out.println(i);
    }

    @Test
    public void findUserByName(){
        String username="用户1";
        User user = userMapper.getUserByName(username);
        System.out.println(user.toString());
    }
}


自动装配userMapper时报错:


问题:自动装配userMapper时,报“Could not autowire. No beans of 'UserMapper' type found”错

解决:将Autowiring for bean class选项下的Severity设置为Warning即可。



运行时报错:


报错:Could not resolve type alias 'UserEntityMap'. Cause: java.lang.ClassNotFoundException: Cannot find class: UserEntityMap

解决:


虽然测试能通过,但是有junit Vintage报错


解决:引入的@Test的包是org.junit.Test 不是org.junit.jupiter.api.Test

另外:

junit-vintage-engine 是 JUnit 4 中使用的测试引擎。
junit-jupiter-engine 是 JUnit 5 中使用的测试引擎。


参考链接:https://blog.csdn.net/qq_38425719/article/details/106603736



关于id自增的一些补充


  • 数据库主键自增AUTO_INCREMENT,则数据删除后,主键还是会继续增加,即主键使用过一次将不会再次使用。

  • 例如:这个表中有10条数据,主键为1-10不间断的数字,那删除第十条数据,继续插入的话,id则会变成11,而不是10。通俗的说就是主键使用过一次将不会再次使用。




posted @   卡卡发  阅读(1521)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示