Test parametrico con metodi generici
-
03-07-2019 - |
Domanda
In NUnit 2.5 puoi farlo:
[TestCase(1,5,7)]
public void TestRowTest(int i, int j, int k)
{
Assert.AreEqual(13, i+j+k);
}
È possibile eseguire test parametrici.
Ma mi chiedo se puoi farlo o no, test parametrico con metodo di test generico? Cioè:.
[TestCase <int>("Message")]
public void TestRowTestGeneric<T>(string msg)
{
Assert.AreEqual(5, ConvertStrToGenericParameter<T>(msg));
}
O qualcosa di simile.
Soluzione
Ecco la citazione dalla nota di rilascio di NUnit 2.5 testo del link
I metodi di prova con parametri possono essere generico. NUnit dedurrà il corretto implementazione da utilizzare in base al tipi di parametri forniti. I metodi di test generici sono supportati in clasi sia generici che non generici.
In base a ciò, è possibile avere un metodo di prova generico in classe non generica. Come?
Non capisco bene il commento di Jeff. In .net generics è sia il tempo di compilazione che il tempo di esecuzione. Possiamo usare la riflessione per scoprire l'attributo del test case associato a un metodo, scoprire il parametro generico e usare nuovamente la riflessione per chiamare il metodo generico. Funzionerà, no?
Aggiornamento: OK, ora so come e spero che non sia troppo tardi. È necessario che il tipo generico sia nell'elenco dei parametri. Ad esempio:
[TestCase((int)5, "5")]
[TestCase((double)2.3, "2.3")]
public void TestRowTestGeneric<T>(T value, string msg)
{
Assert.AreEqual(value, ConvertStrToGenericParameter<T>(msg));
}
Altri suggerimenti
Puoi personalizzare GenericTestCaseAttribute
[Test]
[GenericTestCase(typeof(MyClass) ,"Some response", TestName = "Test1")]
[GenericTestCase(typeof(MyClass1) ,"Some response", TestName = "Test2")]
public void MapWithInitTest<T>(string expectedResponse)
{
// Arrange
// Act
var response = MyClassUnderTest.MyMethod<T>();
// Assert
Assert.AreEqual(expectedResponse, response);
}
Ecco l'implementazione di GenericTestCaseAttribute
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class GenericTestCaseAttribute : TestCaseAttribute, ITestBuilder
{
private readonly Type _type;
public GenericTestCaseAttribute(Type type, params object[] arguments) : base(arguments)
{
_type = type;
}
IEnumerable<TestMethod> ITestBuilder.BuildFrom(IMethodInfo method, Test suite)
{
if (method.IsGenericMethodDefinition && _type != null)
{
var gm = method.MakeGenericMethod(_type);
return BuildFrom(gm, suite);
}
return BuildFrom(method, suite);
}
}
Crea un metodo privato e chiamalo:
[Test]
public void TypeATest()
{
MyTest<TypeA>();
}
[Test]
public void TypeBTest()
{
MyTest<TypeB>();
}
private void MyTest<T>()
{
// do test.
}