mem*_*und 64 java junit spring spring-test
由于重复@RunWith注释,以下代码无效:
@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(Parameterized.class)
@SpringApplicationConfiguration(classes = {ApplicationConfigTest.class})
public class ServiceTest {
}
Run Code Online (Sandbox Code Playgroud)
但是我如何结合使用这两个注释呢?
key*_*oxy 80
您可以使用Spring提供的SpringClassRule和SpringMethodRule
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.springframework.test.context.junit4.rules.SpringClassRule;
import org.springframework.test.context.junit4.rules.SpringMethodRule;
@RunWith(Parameterized.class)
@ContextConfiguration(...)
public class MyTest {
@ClassRule
public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule();
@Rule
public final SpringMethodRule springMethodRule = new SpringMethodRule();
...
Run Code Online (Sandbox Code Playgroud)
mav*_*azy 35
至少有两个选项可以做到这一点:
您的测试需要看起来像这样:
@RunWith(Parameterized.class)
@ContextConfiguration(classes = {ApplicationConfigTest.class})
public class ServiceTest {
private TestContextManager testContextManager;
@Before
public void setUpContext() throws Exception {
//this is where the magic happens, we actually do "by hand" what the spring runner would do for us,
// read the JavaDoc for the class bellow to know exactly what it does, the method names are quite accurate though
this.testContextManager = new TestContextManager(getClass());
this.testContextManager.prepareTestInstance(this);
}
...
}
Run Code Online (Sandbox Code Playgroud)有一个github项目https://github.com/mmichaelis/spring-aware-rule,它建立在以前的博客上,但是以一种通用的方式增加了支持
@SuppressWarnings("InstanceMethodNamingConvention")
@ContextConfiguration(classes = {ServiceTest.class})
public class SpringAwareTest {
@ClassRule
public static final SpringAware SPRING_AWARE = SpringAware.forClass(SpringAwareTest.class);
@Rule
public TestRule springAwareMethod = SPRING_AWARE.forInstance(this);
@Rule
public TestName testName = new TestName();
...
}
Run Code Online (Sandbox Code Playgroud)因此,您可以拥有一个实现其中一种方法的基本类,以及从中继承的所有测试.
| 归档时间: |
|
| 查看次数: |
27464 次 |
| 最近记录: |