SpringBoot整合Junit框架(学习笔记四)

1.通学习前面的文章,创建项目,项目名自定义。

 2.引入starter-test起步依赖

 <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

将上面的依赖引入pom.xml文件即可

3.编写一个Service类

在main/java/com.example.springboottest右击新建java class 

在框中输入UserService 然后回车

在UserService类中,输入 代码做测试

package com.example.springboottest;

import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserService {

    public void printDate(){
        System.out.println(new Date());
    }

  
}

4.编写测试类

方法一

我们在test/java/com.example新建一个test包

在右击test包,选中new——》在选中java class——》新建一个userServiceTest类

 在该类输入如下代码

package com.example.test;

import com.example.springboottest.SpringBootTestApplication;
import com.example.springboottest.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;


@SpringBootTest(classes = SpringBootTestApplication.class)//不同包名的情况下需要写入引导类
public class UserServiceTest {


    @Autowired
    private UserService userService;

    @Test
    public void printDate(){
        userService.printDate();
    }

}

打印输出结果为:

Sat Jul 30 21:19:42 CST 2022

方法二

在test/java/目录下直接右击——》右击New——》选中package

输入和main/java路径下一样的包名,也就是UserService同包名

在包下新建java calss 文件,文件名为UserServiceTest

 

这个test/java/com.example.springboottest包下的UserServiceTest文件中输入如下代码

package com.example.springboottest;

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

@SpringBootTest//不同包名的情况下需要写入引导类
public class UserServiceTest {

    @Autowired
    private UserService userService;

    @Test
    public void printDate(){
        userService.printDate();
}
  
}

运行结果为:

Sat Jul 30 21:25:23 CST 2022

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值