NUnit 3:OneTimeSetUp不触发

8
在 NUnit 3 中,他们用 "OneTimeSetUp" 替换了属性 "TestFixtureSetUp"。然而,除非我是个十足的白痴,否则它似乎并没有实际起作用。
下面是我的代码:
[TestFixture]
public class DiskServiceTests
{
    private readonly Mock<IDriveInfoWrapper> _driveInfoWrapper = new Mock<IDriveInfoWrapper>();
    private IDiskService _diskService;

    [OneTimeSetUp]
    public void Init()
    {
        _diskService = new DiskService(_driveInfoWrapper.Object);
    }

    [Test]
    public void GetDriveInfo_ShouldReturnDriveInfo()
    {
        // Act
        var result = _diskService.GetDriveInfo();

        // Assert
        Assert.IsNotNull(result);
    }
}

测试将会开始,但是它从未进入Init()函数,所以 _diskService 为null。我做错了什么吗?还是这可能是一个bug?
2个回答

8

谢谢,伙计。我不知道这个属性依赖于Resharper才能工作。我现在会将属性保留为“TestFixtureSetUp”,因为这会质疑我们的构建服务器是否能够正确运行测试。 - Tom
+1 这就解释了为什么我的单元测试在 Visual Studio 中通过,但在控制台运行时却失败了。原来我的 nunit-console.exe 版本过旧了! - inejwstine
好吧,现在它已经被支持了,但今天它又随机决定再次忽略OneTimeSetup。切换到VS的文本资源管理器解决了问题。 - jeromej

0
在我的情况下,主要问题是主类中的命名空间与测试类中的命名空间前缀不匹配。
根据 SetUpFixtureAttribute 文档:“将一个类标识为包含 NUnit.Framework.OneTimeSetUpAttribute 或 NUnit.Framework.OneTimeTearDownAttribute 方法的类,用于所有给定命名空间下的测试夹具。”
namespace Project.Application.SubcutaneousTests;
[SetUpFixture]
public partial class Testing
{
    [OneTimeSetUp]
    public void RunBeforeAnyTests()
    {
    }
}

在测试类中,我有一个错误的前缀命名空间 "namespace Project.Application.Common;"。我只是将它更改为 "namespace Project.Application.SubcutaneousTests.Common;"。
namespace Project.Application.SubcutaneousTests.Common;
[TestFixture()]
public class MyTests
{
    [Test]
    public void XTest1()
    {
        Debug.Print("Finished.");
    }
}

在这之后,OnTimeSetUp开始触发。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接