首页 > 解决方案 > 有没有办法在一起运行多个测试时在单元测试用例中模仿 startup.cs 的功能?

问题描述

我正在尝试测试一些使用静态类的代码。静态类有一个初始化方法,只能调用一次,第二次调用会抛出异常。我有多个测试用例来测试需要访问静态类的代码。在代码中,初始化是在 startup.cs 中完成的。我如何为测试用例做类似的事情。我正在使用 x-unit 进行单元测试。

 public static class UniqueId
{
    public static void Initialize()
    {
        if (_generator != null)
            throw new Exception("Already initialized.");
        _generator = new IdGenerator();
    }


    private static IdGenerator _generator = null;
    
    public static BigId NextId()
    {
        if (_generator == null)
            throw new Exception("Not initialized.");
        return _generator.NextId();
    }
}

我要测试的代码:

public string GenerateId
{
    return UniqueId.NextId().ToString()
}

标签: c#.net-corexunit

解决方案


在您的特定情况下,您需要将您的类设置为实现 IDisposible 并在您想要销毁它时调用 Dispose() 。

这里有一个例子:

namespace Prime.UnitTests.Services
{
    [TestFixture]
    public class YourClassTest
    {

        [SetUp]
        public void SetUp()
        {
            //some configs...
        }

        [Test]
        public void Test_size_String_1()
        {
            UniqueId.Initialize();
            Assert.IsFalse(UniqueId.NextId().ToString() == 10); // quick example...
            UniqueId.Dispose();
        }

        [Test]
        public void Test_size_String_2XPTO()
        {
            UniqueId.Initialize();
            Assert.IsFalse(UniqueId.NextId().ToString() == 115); // quick example...
            UniqueId.Dispose();
        }

    }
}


public static class UniqueId : IDisposable  
{
    public static void Initialize()
    {
        if (_generator != null)
            throw new Exception("Already initialized.");
        _generator = new IdGenerator();
    }


    private static IdGenerator _generator = null;
    
    public static BigId NextId()
    {
        if (_generator == null)
            throw new Exception("Not initialized.");
        return c.NextId();
    }

    public void Dispose()
    {
        _generator?.Dispose(); //Depends of the context of your IdGenerator
        //or
        _generator == null;
    }
}

推荐阅读