c# - Visual Studio 单元测试拒绝运行

标签 c# unit-testing visual-studio-2013

我开始使用 Visual Studio 和内置的单元测试器测试一个学校项目。该项目是用 C# 编写的类库。到目前为止,我所有的测试都有效。但是,我仍然有 1 个测试无法运行。它没有通过或失败,只是没有运行。没有给出错误消息,我无法让它运行或调试或任何东西。这是我正在尝试的测试:

[TestMethod()]
    public void PublicDecimalEqualityTest2()
    {
        Formula form1 = new Formula("2.3232000+3.00");
        Formula form2 = new Formula("2.3232+3.0000");
        Assert.IsTrue(form1==form2);
    }

我的类的“==”运算符定义正确。奇怪的是,这个测试运行并通过了:

[TestMethod()]
    public void PublicDecimalEqualityTest()
    {
        Formula form1 = new Formula("2.3232000+3.00");
        Formula form2 = new Formula("2.3232+3.0000");
        Assert.IsTrue(form1.Equals(form2));
    }

知道为什么发布的第一个测试无法运行吗?

编辑:这是 == 运算符的代码:

public static bool operator ==(Formula f1, Formula f2) {
    if (f1==null && f2==null)
    { return true; }
    if (f1==null || f2==null)
    {return false;}
    if (f1.GetFormulaBasic()==f2.GetFormulaBasic())
    { return true; }
    else
    { return false;}
}

GetFormulaBasic() 只是从类中返回一个私有(private)字符串。希望这会有所帮助。

最佳答案

我的猜测是正确的。当您检查 null 时,您正在您的实现中调用运算符 == 。将 == 替换为 Object.ReferenceEquals 以测试运算符内的 null。在这里,简化了一点:

public static bool operator ==(Formula f1, Formula f2)
{
    if (object.ReferenceEquals(f1, f2))
    { 
        return true; 
    }
    if (object.ReferenceEquals(f1, null) || object.ReferenceEquals(f2, null))
    {
        return false;
    }

    return f1.GetFormulaBasic() == f2.GetFormulaBasic();
}

关于c# - Visual Studio 单元测试拒绝运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26070560/

相关文章:

c# - 在运行时获取 C# 中属性的字符串表示形式

c# - 过度使用委托(delegate)对性能来说是个坏主意吗?

javascript - $injector 在我的测试中不起作用,为什么?

c++ - 强制一个特定的构造函数只在某些代码中使用,别处

c# - Visual Studio 2013 - 如何在控制台中查看输出?

.net - SQL Server 数据库项目在 VS 2013 中不兼容

c# - Winforms:具有数千个用户控件的可滚动 FlowLayoutPanel - 如何防止内存泄漏并以正确的方式处理对象?

c# - 在 asp.net 中重新加载页面期间 Cookie 被清除

unit-testing - 如何测试 Rust 中的可选功能?

c# - 无法在 Visual Studio 2013 上找到 Visual Studio 安装程序项目