2012-08-01 18 views
10

almaceno información variada sobre una prueba dada (IDs para múltiples sistemas de seguimiento de errores) en un atributo de este modo:¿Cómo obtener los atributos del método de prueba unitaria en tiempo de ejecución desde dentro de una ejecución de prueba NUnit?

[TestCaseVersion("001","B-8345","X543")] 
public void TestSomethingOrOther() 

Con el fin de ir a buscar esta información durante el curso de una prueba, que escribió el código de abajo:

 public string GetTestID() 
    { 
     StackTrace st = new StackTrace(1); 
     StackFrame sf; 
     for (int i = 1; i <= st.FrameCount; i++) 
     { 
      sf = st.GetFrame(i); 
      if (null == sf) continue; 
      MethodBase method = sf.GetMethod(); 
      if (method.GetCustomAttributes(typeof(TestAttribute), true).Length == 1) 
      { 
       if (method.GetCustomAttributes(typeof(TestCaseVersion), true).Length == 1) 
       { 
        TestCaseVersion tcv = 
         sf.GetMethod().GetCustomAttributes(typeof(TestCaseVersion), true).OfType<TestCaseVersion>() 
          .First(); 
        return tcv.TestID; 
       } 
      } 
     } 

el problema es que cuando se ejecuta a través de pruebas NUnit en modo de lanzamiento, el método que debe tener el nombre de la prueba y estos atributos se sustituye por la siguiente:

System.RuntimeMethodHandle._InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeType typeOwner) 
    at System.RuntimeMethodHandle.InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeType typeOwner) 
    at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) 
    at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) 
    at NUnit.Core.Reflect.InvokeMethod(MethodInfo method, Object fixture, Object[] args) 

ACTUALIZACIÓN Para cualquiera que esté interesado, terminé la implementación del código de la siguiente manera (de modo que cualquiera de los valores de los atributos se podría tener acceso, sin cambiar nada del código existente que utiliza TestCaseVersion atributo:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Method, AllowMultiple = false)] 
public class TestCaseVersion : PropertyAttribute 
{ 
    public TestCaseVersion(string testCaseCode, string story, string task, string description) 
    { 
     base.Properties.Add("TestId", testCaseCode); 
     base.Properties.Add("Description", description); 
     base.Properties.Add("StoryId", story); 
     base.Properties.Add("TaskId", task); 
    } 
} 

public string GetTestID() 
{ 
    return TestContext.CurrentContext.Test.Properties["TestId"]; 
} 
+0

¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡ Te daría un segundo voto si pudiera :-) –

Respuesta

8

Si estás bien con tener una prueba del hilo versión caso de un solo valor (es decir, en lugar de "001, B-8345, X543""001","B-8345","X543"), que debe ser capaz de hacer uso de la funcionalidad disponible en TestContextNUnit 2.5.7 y más alto .

En concreto, se podría definir y utilizar un contexto de prueba Property atributo TestCaseVersion así:

[Test, Property("TestCaseVersion", "001, B-8345, X543")] 
public void TestContextPropertyTest() 
{ 
    Console.WriteLine(TestContext.CurrentContext.Test.Properties["TestCaseVersion"]); 
} 

ACTUALIZACIÓN Por cierto, si hace que desee utilizar una representación de varios valores de la prueba versión de caso, puede definir varias propiedades, como esta:

[Test, Property("MajorVersion", "001"), 
Property("MinorVersion", "B-8345"), Property("Build", "X543")] 
public void TestContextPropertyTest() 
{ 
    Console.WriteLine(TestContext.CurrentContext.Test.Properties["MajorVersion"]); 
    Console.WriteLine(TestContext.CurrentContext.Test.Properties["MinorVersion"]); 
    Console.WriteLine(TestContext.CurrentContext.Test.Properties["Build"]); 
} 
+0

Gracias, esa es la única solución que pude encontrar también. Ojalá hubiera una forma de obtener otros atributos del método de prueba real, pero esto tendrá que ver – breed052

0

Puede ser que no entiendo su idea, pero ¿por qué no utilizar una solución mucho más simple?

[TestCase(TestName = "001, B-8345, X543")] 
public void TestSomethingOrOther() 
+0

Estoy contento con TestName en NUnit TestContext, pero quiero proporcionar múltiples valores adicionales simplemente agregándolos al atributo. Si los utilizo en un atributo TestCase, tendría que agregarlos como parámetros al método de prueba, y aún no serían accesibles sin agregar código adicional a cada prueba. – breed052

+0

Pero, ¿cómo vas a usar 'GetTestID()', agregar información adicional para afirmar mensajes? – Akim

+0

Uso GetTestID en un método que todas las pruebas llaman para registrar los resultados de las pruebas. – breed052

Cuestiones relacionadas