2013-05-10 16 views
7

Utilizzando Xunit, come posso ottenere il nome del test attualmente in esecuzione?Ottieni il nome del test corrente in Xunit

public class TestWithCommonSetupAndTearDown : IDisposable 
    { 
    public TestWithCommonSetupAndTearDown() 
    { 
     var nameOfRunningTest = "TODO"; 
     Console.WriteLine ("Setup for test '{0}.'", nameOfRunningTest); 
    } 

    [Fact] 
    public void Blub() 
    { 
    } 

    public void Dispose() 
    { 
     var nameOfRunningTest = "TODO"; 
     Console.WriteLine ("TearDown for test '{0}.'", nameOfRunningTest); 
    } 
    } 

Edit:
In particolare, sono alla ricerca di un sostituto per NUnits TestContext.CurrentContext.Test.Name proprietà.

risposta

8

È possibile utilizzare BeforeAfterTestAttribute di risolvere il caso. Ci sono alcuni modi per risolvere il problema usando Xunit, che sarebbe quello di creare sottoclasse di TestClassCommand, o FactAttribute e TestCommand, ma penso che BeforeAfterTestAttribute sia il modo più semplice. Controlla il codice qui sotto.

public class TestWithCommonSetupAndTearDown 
{ 
    [Fact] 
    [DisplayTestMethodName] 
    public void Blub() 
    { 
    } 

    private class DisplayTestMethodNameAttribute : BeforeAfterTestAttribute 
    { 
     public override void Before(MethodInfo methodUnderTest) 
     { 
      var nameOfRunningTest = "TODO"; 
      Console.WriteLine("Setup for test '{0}.'", methodUnderTest.Name); 
     } 

     public override void After(MethodInfo methodUnderTest) 
     { 
      var nameOfRunningTest = "TODO"; 
      Console.WriteLine("TearDown for test '{0}.'", methodUnderTest.Name); 
     } 
    } 
} 
0

Non riesco a parlare con xUnit ... ma questo ha funzionato per me in VS Testing. Potrebbe valere la pena di un colpo.

Riferimento: How to get the name of the current method from code

Esempio:

[TestMethod] 
public void TestGetMethod() 
{ 
    StackTrace st = new StackTrace(); 
    StackFrame sf = st.GetFrame(0); 
    MethodBase currentMethodName = sf.GetMethod(); 
    Assert.IsTrue(currentMethodName.ToString().Contains("TestGetMethod")); 
} 
+0

Grazie per la risposta. Sono a conoscenza di questa opzione (utilizzandola in questo momento) e alla ricerca di un'altra opzione. –

Problemi correlati