1. 程式人生 > 其它 >測試——@RunWith(SpringRunner.class)和@SpringBootTest註解

測試——@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