測試——@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。通俗的說就是主鍵使用過一次將不會再次使用。





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM