大家好,我在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)
这样就没有问题。
我的问题是,如何处理能直接使用自定义的注解完成测试类?
哈哈吧