4.整合第三方技术【整合JUnit】

发布于:2024-06-26 ⋅ 阅读:(152) ⋅ 点赞:(0)

目录

1.创建项目:

2.导入测试对应的starter

3.添加测试对象

    3.1 添加Prodcut接口文件

    3.2 添加ProdcutImpl文件

    3.3 测试类添加测试文件,并开始测试

4.测试类文件解析

4.1.测试类使用@SpringBootTest修饰

4.2使用自动装配的形式添加要测试的对象


1.创建项目:

点击下一步:

点击创建

2.导入测试对应的starter

如果你的项目使用Maven作为构建工具,那么pom.xml文件中会自动帮你注入依赖如下所示:

如果没有可以自行注入:

<dependencies>
    <!-- 其他依赖项 -->

    <!-- Spring Boot Starter Test -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

3.添加测试对象

    3.1 添加Prodcut接口文件

package com.example.junit.Interface;

public interface Product {
    public void save();
}

    3.2 添加ProdcutImpl文件

package com.example.junit.impl;

import com.example.junit.Interface.Product;
import org.springframework.stereotype.Repository;

@Repository
public class ProductImpl implements Product {
    @Override
    public void save() {
        System.out.println("product is running!!!");
    }
}

    3.3 测试类添加测试文件,并开始测试

package com.example.junit;

import com.example.junit.impl.ProductImpl;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

//加载配置类
@SpringBootTest(classes = JunitApplication.class)
//@ContextConfiguration(classes = JunitApplication.class)
class JunitApplicationTests {

     //1.注入要测试的对象
    @Autowired
    private ProductImpl productController;

    
    @Test
    void contextLoads() {
        //2.执行要测试的的对象对应的方法
        productController.save();


    }

}

4.测试类文件解析


4.1.测试类使用@SpringBootTest修饰

  • 测试类如果存在于引导类所在包或子包中无需指定引导类
  • 测试类如果不存在于引导类所在的包或子包中需要通过classes属性指定引导类

4.2使用自动装配的形式添加要测试的对象

名称:@SpringBootTest

  • 类型:测试类注解
  • 位置:测试类定义上方
  • 作用:设置JUnit加载的SpringBoot启动类
  • 范例:

@SpringBootTest(classes = JunitApplication.class)

class JunitApplicationTests{}

  • 相关属性

        classes:设置SpringBoot启动类

注意事项:

如果测试类在SpringBoot启动类的包或子包中,可以省略启动类的设置,也就是省略classes的设定


网站公告

今日签到

点亮在社区的每一天
去签到