轉:how-to-run-junit-springjunit4classrunner-with-parametrized

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

    ...
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章