【问题标题】:Object reference not set to an instance of an object when trying to xUnit tests尝试 xUnit 测试时未将对象引用设置为对象的实例
【发布时间】:2020-11-03 23:05:03
【问题描述】:

我有一个实现计时器的类。我想为该类进行 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;
        }

【问题讨论】:

  • @PavelAnikhouski 我不明白为什么为空。我试图做类似“私人只读 GuessingGameTimer t = GuessingGameTimer(3000)”之类的事情,但仍然不起作用
  • 但是你又在测试构造函数中明确地分配了 null 。请记住,在单元测试项目中,默认情况下不会设置依赖注入。所以构造函数参数将为空。

标签: c# asp.net unit-testing testing xunit


【解决方案1】:
    public GuessingGameTimerTests()
    {
        this.t = new GuessingGameTimer(3000);
    }

【讨论】:

  • 之前尝试过,但出现以下错误“以下构造函数参数没有匹配的夹具数据”
  • 你能发布你完整的测试课程吗?我也在回答中清理了构造函数参数。确保您的构造函数不接受任何参数。
猜你喜欢
  • 1970-01-01
  • 2016-08-01
  • 1970-01-01
  • 2013-02-19
  • 2012-07-23
  • 2013-08-18
  • 1970-01-01
  • 1970-01-01
  • 2021-01-31
相关资源
最近更新 更多