SpringBoot添加测试

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


一、在POM.XML中添加对应的依赖包

<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.9.3</version>
<scope>test</scope>
</dependency>


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

二、创建简单类

1.右键生成测试类

三、代码示例

代码如下(示例):

package com.ys;


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

@SpringBootTest
public class test {
@Test
public void name() {
System.out.println("简单测试");
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在使用 Spring Boot 进行开发时,可以使用 JUnit、Mockito、AssertJ 等测试框架对应用程序进行单元测试。为了方便测试,可以添加测试的类来对 Spring Boot 应用程序进行集成测试添加测试的类的步骤如下: 1. 在测试源代码目录(默认为 src/test/java)下创建一个测试类。 2. 在类上添加 @SpringBootTest 注解,该注解会告诉 Spring Boot 启动一个完整的应用程序上下文来进行测试。 3. 如果需要使用模拟对象进行测试,则可以使用 @MockBean 注解注入模拟对象。 4. 编写测试方法,在方法中编写测试逻辑。 例如,下面是一个简单的可测试类示例: ```java @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class) public class MyTest { @Autowired private MyService myService; @MockBean private MyRepository myRepository; @Test public void testMyMethod() { // 设置模拟对象的行为 when(myRepository.findById(1L)).thenReturn(Optional.of(new MyEntity(1L, "foo"))); // 调用被测试方法并进行断言 String result = myService.myMethod(1L); assertThat(result).isEqualTo("foo"); } } ``` 在该示例中,我们创建了一个名为 MyTest测试类,并使用 @SpringBootTest 注解指定了要测试的 Spring Boot 应用程序类(Application.class)。我们还使用了 @Autowired 注解注入了一个 MyService 类型的对象,并使用 @MockBean 注解注入了一个 MyRepository 类型的模拟对象。 在测试方法 testMyMethod 中,我们设置了模拟对象的行为,并调用了被测试方法 myMethod,并使用 assertThat 断言方法进行测试
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值