使用通用方法进行参数测试 [英] Parametric test with generic methods

查看:59
本文介绍了使用通用方法进行参数测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 NUnit 2.5 中你可以这样做:

In NUnit 2.5 you can do this:

[TestCase(1,5,7)]
public void TestRowTest(int i, int j, int k)
{
  Assert.AreEqual(13, i+j+k);
}

你可以做参数测试.

但是我想知道您是否可以这样做,使用通用测试方法进行参数测试?即:

But I wonder whether you can do this or not, parametric test with generic test method? I.e.:

[TestCase <int>("Message")]
public void TestRowTestGeneric<T>(string msg)
{
  Assert.AreEqual(5, ConvertStrToGenericParameter<T>(msg));
}

或类似的东西.

推荐答案

这里引用 NUnit 2.5 发行说明 链接文本

Here is the quote from the release note of NUnit 2.5 link text

参数化测试方法可能是通用的.NUnit 会推导出正确的使用基于提供的参数类型.支持通用测试方法泛型和非泛型类.

Parameterized test methods may be generic. NUnit will deduce the correct implementation to use based on the types of the parameters provided. Generic test methods are supported in both generic and non-generic clases.

据此,可以在非泛型类中具有泛型测试方法.怎么样?

According to this, it is possible to have generic test method in non-generic class. How?

我不太明白杰夫的评论.在 .net 中泛型既是编译时又是运行时.我们可以使用反射找出与方法关联的测试用例属性,找出泛型参数,然后再次使用反射来调用泛型方法.它会起作用,不是吗?

I don't quite understand Jeff's comment. In .net generics is both compile-time and run-time. We can use the reflection to find out the test case attribute associated with a method, find out the generic parameter, and again use reflection to call the generic method. It will work, no?

更新:好的,我现在知道了,希望现在还为时不晚.您需要在参数列表中包含泛型类型.例如:

Update: OK, I now know how and hope it is not too late. You need the generic type to be in the parameter list. For example:

[TestCase((int)5, "5")]
[TestCase((double)2.3, "2.3")]
public void TestRowTestGeneric<T>(T value, string msg)
{
  Assert.AreEqual(value, ConvertStrToGenericParameter<T>(msg));
}

这篇关于使用通用方法进行参数测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆