转:how-to-run-junit-springjunit4classrunner-with-parametrized(spring-test如何与junit的Parameterized结合)

original: https://stackoverflow.com/questions/28560734/how-to-run-junit-springjunit4classrunner-with-parametrized/28561473

@RunWith(Parameterized.class)
@WebAppConfiguration
@ContextConfiguration({"classpath:springmvc.xml"})
public class SpringTestWithParametersBase {
    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext wac;

    @Autowired
    @Qualifier("xx")
    private Filter filter;

    private TestContextManager testContextManager;

    @Before
    public void setup() throws Exception {
        //https://stackoverflow.com/questions/28560734/how-to-run-junit-springjunit4classrunner-with-parametrized/28561473
        //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);

        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)
                .addFilter(filter, "/api/v2/*")
                .build();

        doSetup();
    }

    protected void doSetup() {
    }

    protected MockMvc getMockMvc() {
        return mockMvc;
    }
    
    @Parameterized.Parameters(name = "{index}:{0}")
    public static Collection addedNumbers() {
        return Arrays.asList(new Object[][]{
                {"/xxxx", "", status().isNotFound()}
        });
    }
}

There is a github project https://github.com/mmichaelis/spring-aware-rule, which builds on previous blog, but adds support in a generalized way

@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();

    ...
}
posted @ 2020-09-06 19:41  liqipeng  阅读(55)  评论(0编辑  收藏  举报