在 nUnit 中构建 TextFixture
Structuring TextFixtures in nUnit
在对某些 class 进行单元测试时,需要针对 class 中的不同数据组合测试相同的方法。这可以通过编写多个 TextFixture 并为每个重复相同的测试方法来实现,如下所示。
[TextFixture]
public class WhenBuildingLongFoo
{
private Foo foo;
[Setup]
public void Creating()
{
foo = new Foo(){Height = new FooHeight(200)};
}
[Test]
public void ReturnsValidHeight()
{
Assert.AreEqual(200, foo.Height);
}
}
[TextFixture]
public class WhenBuildingShortFoo
{
private Foo foo;
[SetUp]
public void Creating()
{
foo = new Foo(){Height=newFooHeight(2);
}
[Test]
public void ReturnsValidHeight()
{
Assert.AreEqual(2, foo.Height);
}
}
- 构建此类固定装置的最佳方法是什么,以便方法 ReturnsValidHeight 只被编写一次?
我想到了在公共命名空间中创建一个 public 静态 class 实用程序,它有这个方法;但你能建议更好的吗?
比如用这样的方法创建一个抽象 class 然后从中派生固定装置?
- 如何在灯具之间重用设置,只是改变值?
使用 TestCase
属性 运行 使用不同输入值的相同测试。这将减少很多重复代码。 SetUp
方法在您的情况下也不是必需的。
[TextFixture]
public class FooTests
{
[Test]
[TestCase(200)]
[TestCase(2)]
public void ReturnsValidHeight(int expectedHeight)
{
var foo = new Foo { Height = new FooHeight(expectedHeight) };
Assert.AreEqual(expectedHeight, foo.Height);
}
}
您可以将此库作为测试编写的替代方案:
https://www.nuget.org/packages/Heleonix.Testing.NUnit/
您以 JavaScript 的 Jasmine 或 Jest 的方式描述 AAA 或 GWT 风格的测试。
您的测试变得更具可读性和更容易获得支持。使用 TestCase 属性,您最终可能会得到复杂的测试,即使在几个月内也很难理解
在对某些 class 进行单元测试时,需要针对 class 中的不同数据组合测试相同的方法。这可以通过编写多个 TextFixture 并为每个重复相同的测试方法来实现,如下所示。
[TextFixture]
public class WhenBuildingLongFoo
{
private Foo foo;
[Setup]
public void Creating()
{
foo = new Foo(){Height = new FooHeight(200)};
}
[Test]
public void ReturnsValidHeight()
{
Assert.AreEqual(200, foo.Height);
}
}
[TextFixture]
public class WhenBuildingShortFoo
{
private Foo foo;
[SetUp]
public void Creating()
{
foo = new Foo(){Height=newFooHeight(2);
}
[Test]
public void ReturnsValidHeight()
{
Assert.AreEqual(2, foo.Height);
}
}
- 构建此类固定装置的最佳方法是什么,以便方法 ReturnsValidHeight 只被编写一次?
我想到了在公共命名空间中创建一个 public 静态 class 实用程序,它有这个方法;但你能建议更好的吗?
比如用这样的方法创建一个抽象 class 然后从中派生固定装置?
- 如何在灯具之间重用设置,只是改变值?
使用 TestCase
属性 运行 使用不同输入值的相同测试。这将减少很多重复代码。 SetUp
方法在您的情况下也不是必需的。
[TextFixture]
public class FooTests
{
[Test]
[TestCase(200)]
[TestCase(2)]
public void ReturnsValidHeight(int expectedHeight)
{
var foo = new Foo { Height = new FooHeight(expectedHeight) };
Assert.AreEqual(expectedHeight, foo.Height);
}
}
您可以将此库作为测试编写的替代方案: https://www.nuget.org/packages/Heleonix.Testing.NUnit/ 您以 JavaScript 的 Jasmine 或 Jest 的方式描述 AAA 或 GWT 风格的测试。 您的测试变得更具可读性和更容易获得支持。使用 TestCase 属性,您最终可能会得到复杂的测试,即使在几个月内也很难理解