【SpringBoot】Junit单元测试遇到的一些问题

本文总结了SpringBoot Junit单元测试中遇到的四个问题及其解决方法:1.测试方法不能有返回值;2.NullPointerException,需添加@RunWith(SpringRunner.class);3.注入失败,需使用@SpringBootTest指定启动类;4.多环境配置导致的问题,通过@ActiveProfiles选择环境。此外,还介绍了如何通过基类优化测试类的注解使用。
摘要由CSDN通过智能技术生成

情况 ①:不能有返回值

@Controller
public class FileControllerTest{

    @Autowired
    private FileController fileController;

    @Test
    public String testDownload(){
        fileController.download("2dd4209286df4f14b703890ccdc3d2ff");
        return "";
    }
}

报错:

java.lang.Exception: Method testDownload() should be void

	at org.junit.runners.model.FrameworkMethod.validatePublicVoid(FrameworkMethod.java:99)
	at org.junit.runners.model.FrameworkMethod.validatePublicVoidNoArg(FrameworkMethod.java:74)
	at org.junit.runners.ParentRunner.validatePublicVoidNoArgMethods(ParentRunner.java:155)
	...

解决办法:测试用例方法是不能有返回值的,必须是public void的

情况 ②:NullPointerException

@Controller
public class FileControllerTest{

    @Autowired
    private FileController fileController;

    @Test
    public void testDownload(){
        fileController.download("2dd4209286df4f14b703890ccdc3d2ff");
    }
}

报错:

java.lang.NullPointerException 
	at com.yealink.version.controller.FileControllerTest.testDownload(FileControllerTest.java:20)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	...

解决办法:意味着要在测试类顶部加上注解@RunWith(SpringRunner.class)

情况 ③: Bean注入失败

                
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值