TDD:当方法根据输入返回不同结果时如何测试结果?
比方说,我有这个类,
public class MyClass
{
public int MyMethod(int? i)
{
throw new NotImplementedException();
}
}
我还有一个
[TestClass]
public class MyClassTest
{
Public void Retur_Int_Greater_Than_Zero_When_Input_Is_Not_Null_And_Zero_Otherwise()
{
// Arrange
var myVar = new MyClass();
int? i = 3;
// Act
var result = myVar.MyMethod(i)
//Assert
//
}
}
我想检查的测试类 - 如果输入为 null 或 0,则结果必须为 0 - 如果输入既不为 null 也不为 0,结果必须是以下的绝对值那个数字。
我该如何表达这些断言?
我可以写这样的话:
if(i.HasValue)
{
//Define the Assert statement inside a If, else constructions...
}
感谢您的帮助
Let's say, I have this class
public class MyClass
{
public int MyMethod(int? i)
{
throw new NotImplementedException();
}
}
I have also a test class
[TestClass]
public class MyClassTest
{
Public void Retur_Int_Greater_Than_Zero_When_Input_Is_Not_Null_And_Zero_Otherwise()
{
// Arrange
var myVar = new MyClass();
int? i = 3;
// Act
var result = myVar.MyMethod(i)
//Assert
//
}
}
I'd like to check - if the input is null or 0, the result must be 0 - if the input is not null nor 0, the result must the absolute value of that number.
How do I express those assertions?
Can I write something like:
if(i.HasValue)
{
//Define the Assert statement inside a If, else constructions...
}
Thanks for helping
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要创建三个测试而不是一个来测试三种不同的场景
如果输入为 null 或 0,则结果必须为 0
如果输入既不为 null 也不为 0,则结果必须为 0该数字的绝对值。
使用 NUnit 中的 TestCase 属性相同
You will need to create three tests instead of one to test three different scenarios
If the input is null or 0, the result must be 0
If the input is not null nor 0, the result must the absolute value of that number.
The same using TestCase attribute from NUnit
不要在测试中使用 if-else 结构。如果您使用 Nunit,请查看参数化测试 - 您可以使用
TestCaseAttribute
来指定您的输入和输出。或者,为不同的输入创建单独的测试。编写单元测试(以及执行 TDD)时可以遵循的另一个原则是测试名称中不应包含
and
。这意味着您正在测试两件事。从您尝试提供的测试名称中,您可以看到您需要拆分测试。示例测试:
另请注意,您必须测试边界条件并确保对每个边界条件都进行了测试。在上面,虽然只写了一个测试,但当它运行时,它运行为 4 个,您甚至可以看到其中一个或多个是否以及何时失败。
同样,测试样本是针对 Nunit 的。如果您使用 MSTest、Xunit、Mbunit 等,语法和断言会有所不同,但原理保持不变。
Don't use if-else contructs in tests. If you are using Nunit have a look at Parameterized tests - you can use the
TestCaseAttribute
to specify your input and output. Or, create separate tests for the different inputs.Another principle that you can follow while writing unit tests ( and doing TDD) is that the test name should not have an
and
in it. That means you are testing two things. From the test name that you are trying to give, you can see that you need to split up the tests.Sample test:
Also note that you have to test the boundary conditions and makes sure you have test for each of them. In the above, though there is just only one test written, when it runs, it runs as 4 and you can even see if and when one or more of them fail.
Again, the test sample is for Nunit. If you are using MSTest, Xunit, Mbunit, etc. the syntax and assertions will differ, but the principles remain the same.