Java annotations - code simplifications

牧云@^-^@ 提交于 2019-11-29 16:08:57

You can place these annotation on a superclass:

@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {
        // My configuration classes
})
public abstract class AbstractIntegrationTest { ... }

.

public class MyServiceTest extends AbstractIntegrationTest { ... }

This approach also allows you to declare common @Autowired dependencies in the base class and customize @ContextConfiguration classes in concrete tests.

The reason your custom composed annotation did not work is that JUnit does not support @RunWith as a meta-annotation. Thus, when you compose your annotation as follows...

@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { /* configuration classes */ })
public @interface IntegrationTests {
}

... it is JUnit that cannot see that you want to use the SpringJUnit4ClassRunner.

Spring Framework 4.0 and greater should have no problem seeing the declarations of @WebAppConfiguration and @ContextConfiguration used as meta-annotations.

In other words, the following should work for you:

@WebAppConfiguration
@ContextConfiguration(classes = { /* configuration classes */ })
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface IntegrationTests {
}

@RunWith(SpringJUnit4ClassRunner.class)
@IntegrationTests
public class MyServiceTest {
    @Autowired
    private MyService service;

    @Test
    public void myTest() {
        assertNotNull(service);
    }
}

As an alternative, you can use an abstract base test class as recommended by axtavt.

Regards,

Sam (author of the Spring TestContext Framework)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!