這裏JUnit測試是一個單元測試類:與參數化方法
MyUnitTestSetup myUnitTestSetup ;
public void setUp(String myParam){
myUnitTestSetup = new MyUnitTestSetup(myParam);
}
@Test
public void test1(){
setUp("value1");
//do some stuff with myParam = "value1";
}
@Test
public void test2(){
setUp("value2");
//do some stuff with myParam = "value2";
}
我想與「VALUE1」和TEST2用「VALUE2」執行TEST1。參數化單元測試是不是方便,因爲它們將執行測試1的「值1」和「值2」和TEST2的「值1」和「值2這是不是我想要的
我雖然約:
- 通話使用@rule標註每一次我做一個測試的設置方法
:
static String myParam; MyUnitTestSetup myUnitTestSetup ; @Before public void setUp(){ myUnitTestSetup = new MyUnitTestSetup(myParam); } @Rule public TestRule rule = new TestRule() { @Override public Statement apply(final Statement base, final Description desc) { return new Statement() { @Override public void evaluate() throws Throwable { if(desc.getMethodName().equals("test1")) myParam = "value1"; ... } }; } } @Test public void test1(){ //do some stuff with myParam = "value1"; } @Test public void test2(){ //do some stuff with myParam = "value2"; }
但我想知道是否有更清潔&更聰明的方式。我會想到類似的東西:
MyUnitTestSetup myUnitTestSetup ;
@Before
public void setUp(String myParam){
myUnitTestSetup = new MyUnitTestSetup(myParam);
}
@Test(myParam="value1")
public void test1(){
//do some stuff with myParam = "value1";
}
@Test(myParam="value2")
public void test2(){
//do some stuff with myParam = "value2";
}
有什麼想法嗎?
我寫了一個庫名爲參數化,除其他事情,讓你用'@ OnlyIf'或'@ OnlyIfNot'註釋測試做到這一點。不幸的是,我從來沒有得到記錄的東西......但隨時去看看:https://code.launchpad.net/namedparameterizedrunner – yshavit 2012-08-16 18:48:36
可能是這會幫助你http://netbeans.dzone.com/articles/junit-little-beyond-test-after?page = 0, – 2012-08-16 18:53:31