首页 > 解决方案 > 尝试 xUnit 测试时未将对象引用设置为对象的实例

问题描述

我有一个类,我实现了一个计时器。我想为该类进行 xUnit 测试。当我尝试运行测试时出现以下错误

System.NullReferenceException :对象引用未设置为对象的实例。

我在构造函数中所做的不应该修复特定错误?为什么不?有人可以向我解释为什么我得到这个错误吗?

GuessingGameTimerTests.cs

private readonly GuessingGameTimer t;

        public GuessingGameTimerTests(GuessingGameTimer t)
        {
            this.t = t;
        }

        [Fact]
        public void StartTimerTest()
        {
            t.SetTimer(30000);
            bool expected = t.IsEnabled();
            Assert.True(expected);
        }
....

GuessingGameTimer.cs

public class GuessingGameTimer 
    {
        public event EventHandler OnNumberChanged;
        private System.Timers.Timer NumberGeneratorTimer;
        private int replacetime; // Time in seconds
        private int reSetValue; // Time in seconds

        //constractor starts the timer
        public GuessingGameTimer(int replacetime)
        {
            this.replacetime = replacetime;
            reSetValue = replacetime;
            SetTimer(replacetime);
        }
        public void SetTimer(int replacetime)
        {
            NumberGeneratorTimer = new System.Timers.Timer(replacetime);
            NumberGeneratorTimer.Elapsed += OnTick;
            NumberGeneratorTimer.AutoReset = true;
            NumberGeneratorTimer.Enabled = true;
            this.replacetime = getSeconds();
            reSetValue = getSeconds();
        }
        public void ResetTimer()
        {
            NumberGeneratorTimer.AutoReset = true;
            NumberGeneratorTimer.Enabled = true;
            replacetime = reSetValue;
        }

        public void StopTimer()
        {
            NumberGeneratorTimer.Enabled = false;
        }

        public int getSeconds()
        {
            return replacetime;
        }

        public Boolean IsEnabled()
        {
            return NumberGeneratorTimer.Enabled;
        }

标签: c#asp.netunit-testingtestingxunit

解决方案


    public GuessingGameTimerTests()
    {
        this.t = new GuessingGameTimer(3000);
    }

推荐阅读