• 手机版

    扫码体验手机版

  • 微信公众号

    扫码关注公众号

国内首家协议开发

软芯音视解码保护平台

在线
客服

发布
需求

在线
聊天

天盟
APP

天盟APP下载

关注
微信

微信扫一扫访问
顶部

springboot2.0中如何自定义测试注解?

大家好,我在springboot2.0的项目中,进行测试类编写的时候,遇到这么个问题:
项目中有一部分类是通过xml文件的方式加入项目中,所以测试类编写的时候,是通过如下方式:
@RunWith(SpringRunner.class)@SpringBootTest(classes = MySpringApplication.class) //main方法启动springboot的类名@ContextConfiguration(locations = {"classpath:old-beans.xml"})//一部分没有通过注解方式加入进来的beanpublic class SpringApplicationTests {    @Test    public void helloworld() {            System.out.println("Hello world");    }}通过这种方式完成测试,是可以正常运行的。但是因为每个类都需要在头部加入三个注解,或者去继承这个类。所以,我想通过自定义一个注解来简化一下测试类的编写,我的想法如下:

1.定义一个自己的注解,把上面写的注解都加入过来,测试时,使用自己的注解,只写一次就可以。
@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@RunWith(SpringRunner.class)@SpringBootTest(classes = MySpringApplication.class)@ContextConfiguration(locations = {"classpath:old-beans.xml"})public @interface MyTest {}2. 使用时
@MyTest public class PropertiesRead{    @Autowired    private UserProperties userProperties ;        @Test    public void testGetAge(){        int age= userProperties.getDefaultAge();        System.out.println("age:" + age);    }}以上操作会报空指针异常 userProperties没有被注入进来,必须在类头部加入
@RunWith(SpringRunner.class)这样就没有问题。
我的问题是,如何处理能直接使用自定义的注解完成测试类?

免责声明:本内容仅代表回答会员见解不代表天盟观点,请谨慎对待。

版权声明:作者保留权利,不代表天盟立场。

使用道具 举报

全部参与1

自定义注解本身没问题,但是你的自定义注解也没实现具体的功能,类似反射获取@MyTest包含的注解信息吧
在springboot中,确实也有@SpringBootApplication,可是他也必须获取类的注解信息进一步处理的,如果你必须完成这样的功能,可以模仿@SpringBootApplication,再包装一层去管理Test的运行吧,再配合单元测试修改启动入口的main方法
好奇的问一句,你的pom文件应该有配置mainClass属性的插件么?

使用道具 举报

发新帖

发布任务需求已有1031167位用户正在使用天盟网服务

发布分类: *
任务预算: *
需求内容: *
手机号码: *
任务商家报价为
  • 预算价 :
  • 成交价 :
  • 完工期 :
  • 质保期 :

* 最终任务项目以服务商报价、双方协商为准!