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

大家好,我在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)

这样就没有问题。

我的问题是,如何处理能直接使用自定义的注解完成测试类?



精慕门5395394
浏览 1931回答 3
3回答

哈哈吧

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