c# - 尝试 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;
}
解决方案
public GuessingGameTimerTests()
{
this.t = new GuessingGameTimer(3000);
}
推荐阅读
- amazon-web-services - 在 AWS 上托管 Elasticsearch:{"error":"您需要先登录或注册才能继续。"}
- vuex - 不要在突变处理程序之外改变 vuex 存储状态 - Vuetify 小吃吧
- c - 它是一个二叉搜索树。删除元素时出现问题。为什么?
- redis - 如果我重新启动一个 REDIS 实例,删除其他的 PID 和 sock 文件
- regex - 正则表达式捕获和重新定位相同的模式
- android - 使用相同布局显示全视图和半视图时视图的BottomSheetDialog对齐
- javascript - Access Unnamed Value in Ajax Object
- blazor - 悬停并更改图像
- r - 查找自上次面板数据更改以来的累积值变化和时间
- php - Gdex woocommerce 安装问题?