springBoot的测试方法不能用

2023-02-17 20:55:30

springBoot的测试方法不能用

报错:Error running 'DemoApplicationTests.contextLoads': Failed to resolve org.junit.platform:junit-platform-launcher:1.7.1

自动生成的代码:

package com.example.demo;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class DemoApplicationTests {
    @Test
    void contextLoads() {
        System.out.println("ahah");
    }
}

解决办法:
1.添加依赖:(pom.xml)

<dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
</dependency>

2.修改代码(导包错误):

import org.junit.jupiter.api.Test;
修改为:
import org.junit.Test;

3.添加注解:

@RunWith(SpringRunner.class)

4.把测试类和测试方法修改为public

最后代码为:

package cdu.xdc.demo;

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;

import javax.sql.DataSource;
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
    @Autowired
    DataSource dataSource;
    @Test
    public void contextLoads() {
        System.out.println("哈哈哈");
    }
}

成功解决问题!

  • 作者:夏大锤
  • 原文链接:https://blog.csdn.net/qq_42835350/article/details/115542110
    更新时间:2023-02-17 20:55:30