为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

精慕门5395394 2018-09-05 10:42:05
大家好,我在springboot2.0的项目中,进行测试类编写的时候,遇到这么个问题:项目中有一部分类是通过xml文件的方式加入项目中,所以测试类编写的时候,是通过如下方式:@RunWith(SpringRunner.class) @SpringBootTest(classes = MySpringApplication.class) //main方法启动springboot的类名 @ContextConfiguration(locations = {"classpath:old-beans.xml"})//一部分没有通过注解方式加入进来的bean public 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)这样就没有问题。我的问题是,如何处理能直接使用自定义的注解完成测试类?
查看完整描述

3 回答

?
哈哈吧

TA贡献13条经验 获得超3个赞

自定义注解本身没问题,但是你的自定义注解也没实现具体的功能,类似反射获取@MyTest包含的注解信息吧

在springboot中,确实也有@SpringBootApplication,可是他也必须获取类的注解信息进一步处理的,如果你必须完成这样的功能,可以模仿@SpringBootApplication,再包装一层去管理Test的运行吧,再配合单元测试修改启动入口的main方法

好奇的问一句,你的pom文件应该有配置mainClass属性的插件么?

查看完整回答
反对 回复 2018-09-09
  • 精慕门5395394
    精慕门5395394
    mainClass的插件没有配置,pom文件中只有引用的jar,你说的对自定义的处理需要自己处理,这个我没有写,可能就是要自己再去处理下这个注解信息吧。我再看看书,怎么处理这个。 谢谢你了。
  • 3 回答
  • 0 关注
  • 1923 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信