2013-06-21 19 views
5

Voglio ottenere il nome del metodo TestCase attualmente in esecuzione nel metodo @Before. EsempioOttieni il nome del metodo @Test attualmente in esecuzione in @Before in JUNIT

public class SampleTest() 
{ 
    @Before 
    public void setUp() 
    { 
     //get name of method here 
    } 

    @Test 
    public void exampleTest() 
    { 
     //Some code here. 
    } 
} 
+0

http://stackoverflow.com/questions/473401/get-name-of-curren tly-executing-test-in-junit-4? – ivarni

+0

aggiungi un campo 'previousName' nella tua classe di test e imposta il suo valore alla fine di ogni metodo di prova con After – TecHunter

risposta

16

Come discusso here, provare a utilizzare combinazione @Rule e TestName.

Come da prima che il metodo abbia il nome del test.

Annota campi che contengono regole. Tale campo deve essere pubblico, non statico e un sottotipo di TestRule. La Dichiarazione passato al TestRule verrà eseguito alcun Prima metodi, allora il metodo di prova, e infine qualsiasi Dopo metodi, un'eccezione se uno di questi non riescono

Qui è il caso di test utilizzando Junit 4.9

public class JUnitTest { 

    @Rule public TestName testName = new TestName(); 

    @Before 
    public void before() { 
     System.out.println(testName.getMethodName()); 
    } 

    @Test 
    public void test() { 
     System.out.println("test ..."); 
    } 
} 
2

Provare a usare un'annotazione @Rule con org.junit.rules.TestName classe

@Rule public TestName name = new TestName(); 

@Test 
public void test() { 
    assertEquals("test", name.getMethodName()); 
} 
Problemi correlati