據Google結果,JUnit的參數化測試不被Spring 2.5的SpringJUnit4ClassRunner所支援,但仍有法可解,如下:

@RunWith(Parameterized.class)
@ContextConfiguration
(locations= {"classpath*:resources/spring/**/*.xml"})
@TestExecutionListeners( {DependencyInjectionTestExecutionListener.class })
public class EmployeeDaoImplTest
{
    private final TestContextManager testContextManager;

    @Autowired
    private ApplicationContext applicationContext;

 @Autowired
    private EmployeeDao employeeDao;


    private final String cv_loginid;
    private final String cv_username;
    public EmployeeDaoImplTest(String cv_loginid, String cv_username) {
        this.testContextManager = new TestContextManager(getClass());
        this.cv_loginid = cv_loginid;
        this.cv_username = cv_username;
    }

    @Parameters
    public static Collection<String[]> employeeData() {
        return Arrays.asList(new String[][] {
        {"admin", "Administrator" },
        {"guest", "Guest"},
        {"test", "Tester"}});
    }


    @Before
    public void injectDependencies() throws Exception {
        this.testContextManager.prepareTestInstance(this);
    }


    @Test
    public void parameteriedTest() {
        assertEquals(this.cv_username, this.employeeDao.findByLoginId(this.cv_loginid).getCvUsername());
    }
}

  這個作法其實在和JUnit 3.8.1差不多,紅字體是要改變的作法。在JUnit 3.8.1通常在setUp method去initialize Spring context,而這裡@Before就等同於setUp method,只是initialize Spring context工作變成由TestContextManager去做。

  Parameteried的測試架構,看來是利用static會比new instance先執行的特性,取得@Parameters傳回的Collection之後,等於每一輪迭代都要初始化一次TestContext的instance,及傳Collection裡的參數給constructure,有點巨集(Macro)的味道。

arrow
arrow
    全站熱搜

    Jemmy 發表在 痞客邦 留言(0) 人氣()