Springboot junit 测试

本文介绍了如何在SpringBoot项目中正确集成测试,重点讲述了如何仅引入spring-boot-starter-test依赖、测试代码与项目包结构的关系、void方法标记及@Value注解的使用规范。通过实例演示,读者将掌握高效进行单元测试的方法和注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring Boot 集成测试

今天做了一个demo原本把其他的test代码给copy过来记过是不可以的。由于copy了test目录中间出现了些问题,只能自己搞一下了:

引入maven依赖

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

直接使用代码:

/**
 * user:kay三石
 * time: 9:32
 * desc: 测试使用  必须和项目在同一的包下
 **/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = FileServiceApplication.class)
public class MockClass {

    @Value("${local.update.url}")
    private  String localPath;

    @Value("${awsoss.region}")
    private  String ossRegion;

    @Value("${alioss.region}")
    private   String aliOssRegion;

    @Autowired
    private RepositoryMapper repositoryMapper;

    /**
     * 测试添加
     * junit测试 返回值必须为void
     * @return
     */
    @Test
    public void addRepository(){
        Repository repository = new Repository();
        repository.setId(IdUtil.simpleUUID());
        repository.setActive(1);
        repository.setEnvType(1);
        repository.setType(1);
        System.out.println(localPath);
        repository.setPhysicalPath(localPath);
        repository.setCreateDate(new Date());
        repository.setUpdateDate(new Date());
        repositoryMapper.insertSelective(repository);
    }
}

这样就可以完美的使用了。

总结一下:

  • 只需引入一个springboot test 依赖就可以了,不需要引入其他的依赖
  • test的代码必须是和项目在同一个package下,不然会出现@SpringBootTest(classes = FileServiceApplication.class) 找不到spring boot的运行环境,就不可以注入dao或service
  • 标记@Test的方法的返回值必须为void
  • @Value标记的参数不可以为static修饰

具体的也可参考:
参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kay三石

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值