用一种方法对几种不同的结果进行单元测试 [英] Unit testing several different results in one method

查看:33
本文介绍了用一种方法对几种不同的结果进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 NUnit 2.5,我想测试一个接收多个参数的方法.
尝试使用一种测试方法和几个不同的测试用例来测试它们是否合理,或者从长远来看会更难维护(或者只是指出确切的故障)?

I am using NUnit 2.5, and I want to test a method that recieves several parameters.
Is it reasonable to try to test them using one Test method, with several different TestCases, or will it be harder to maintain (Or just pin point the exact failure) in the long run?

我的总体想法是尝试类似

My general idea is to try something like

[TestCase("valid", Result="validasd", 
  Description = "Valid string test, expecting valid answer")]
[TestCase(null, ExpectedException = typeof(ArgumentNullException),
  Description = "Calling with null, expecting exception")]
[TestCase("", ExpectedException = typeof(ArgumentException), 
  Description = "Calling with an empty string, expecting exception")]
public string TestSubString(string value)
{
  return MethodUnderTest(value);
}

这也是推荐的用法吗——没有明确的断言,只是检查返回值?或者我应该坚持正常方式还是在方法内部断言值?

Is it also a recommended usage - without an explicit assert, just checking on the return value? Or should I stick to the normal way or asserting the value inside the method?

推荐答案

我发现 TestCase 属性在测试主要接受一些简单值、用它们计算然后返回结果的方法时很有用.在这些情况下,编写此类测试所需的开销和重复工作会大大减少.

I have found the TestCase attribute to be useful when testing methods that primarily accept some simple values, compute with them, and then return a result. In these cases, it takes substantially less overhead and duplication to write such tests.

当方法需要复杂的对象参数时,这种方法不起作用,因为TestCase属性只能接受原始类型作为输入参数传递给方法.

This approach does not work when the method requires complex object parameters, because the TestCase attribute can only accept primitive types as input parameters to pass to the method.

如果出现以下情况,您可能还需要考虑编写更典型的单元测试:

You may also want to consider writing a more typical unit test if:

  1. 您团队中的其他开发人员不熟悉这种技术
  2. 可能改变或容纳更多参数的方法的签名
  3. 如果要测试的测试用例或值组合不止少数
  4. 您需要以特定顺序执行测试
  5. 您想使用 ReSharper 为 Visual Studio 运行您的测试(它目前可以无法识别 TestCase 属性)
  1. other developers on your team are not familiar with this technique
  2. the signature of the method likely to change or accommodate more parameters
  3. if there are more than a handful of test cases or combinations of values to test
  4. you need the tests to execute in a particular order
  5. you want to run your tests using ReSharper for Visual Studio (it currently does not recognize the TestCase attribute)

这篇关于用一种方法对几种不同的结果进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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