基于SpringBoot的单元测试

3.5.1 添加依赖

<!--test starter-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
</dependency>
​
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <scope>test</scope>
</dependency>

3.5.2 测试类

@RunWith(SpringRunner.class)
@SpringBootTest(classes = ApiApplication.class)
public class UserDAOTest {
​
    @Resource
    private UserDAO userDAO;
​
    @Test
    public void queryUserByName() {
        User user = userDAO.queryUserByName("Lucy");
        System.out.println(user);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中,我们可以使用JUnit来编写和执行单元测试。下面是基于Spring Boot配置单元测试的步骤: 1. 首先,确保在项目的pom.xml文件中添加了JUnit和Spring Boot Test依赖。例如: ``` <dependencies> <!-- 其他依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- 其他依赖 --> </dependencies> ``` 2. 创建一个测试类,并在类上添加`@RunWith(SpringRunner.class)`注解,它会告诉JUnit使用Spring的测试运行器来运行测试。例如: ```java @RunWith(SpringRunner.class) @SpringBootTest public class MyServiceTest { // 测试方法 } ``` 3. 在测试类中,可以使用`@Autowired`注解注入需要测试的组件或服务。例如: ```java @RunWith(SpringRunner.class) @SpringBootTest public class MyServiceTest { @Autowired private MyService myService; // 测试方法 } ``` 4. 编写测试方法,并使用`@Test`注解标记该方法为一个测试方法。例如: ```java @RunWith(SpringRunner.class) @SpringBootTest public class MyServiceTest { @Autowired private MyService myService; @Test public void testSomeMethod() { // 测试逻辑 } } ``` 5. 在测试方法中,可以使用断言来验证期望的结果。例如,使用JUnit的断言方法`assertEquals()`: ```java @RunWith(SpringRunner.class) @SpringBootTest public class MyServiceTest { @Autowired private MyService myService; @Test public void testSomeMethod() { int result = myService.someMethod(); assertEquals(10, result); } } ``` 以上就是基于Spring Boot配置单元测试的基本步骤。你可以根据具体的需求编写更多的测试方法来验证你的代码逻辑是否正确。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值