我在.NET C#项目中使用NUnit
我需要声明historyRecord.InstrType等于InstrType.Nanodac
我有myVal
InstrType
其中InstrType是枚举:
public enum InstrType
{
HydraSbs,
HydraLbs,
HydraSfs,
HydraLfs,
HydraEconomique,
Blind,
Lxio,
Sxio,
Sfse,
T800QVga,
T800SVGa,
Eycon10,
Eycon20,
T2550,
T2750,
Nanodac
}
我需要断言:
Assert.AreEqual(myVal, InstrType.Nanodac)
但它引发了一个例外(“预期Nanodac但是HydraSbs”)。 所以我尝试了这个:
Assert.That(myVal, Is.EqualTo(InstrType.Nanodac))
再次,它提出了同样的例外!
我使用调试器进行了测试,myVal
正确地作为InstrType.Nanodac
我闻到一个枚举糟糕的演员,因为它选择了列表的第一个值(hydraSbs)
答案 0 :(得分:0)
我需要清理并重建项目才能使其正常工作。
答案 1 :(得分:0)
首先,你的原始断言应该可以正常工作,即使参数在技术上是错误的方式。
我的猜测是该值实际上没有正确设置。 因此断言在这种情况下抛出正确的错误消息。
示例代码: TestMethod1显示断言正常工作。 TestMethod2是实际上没有在该行的某处设置的值的示例。
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTestProject1
{
public enum InstrType
{
HydraSbs, // = 0
HydraLbs, // = 1
HydraSfs, // = 2
HydraLfs, // = 3
HydraEconomique, // = 4
Blind, // = 5
Lxio, // = 6
Sxio, // = 7
Sfse, // = 8
T800QVga, // = 9
T800SVGa, // = 10
Eycon10, // = 11
Eycon20, // = 12
T2550, // = 13
T2750, // = 14
Nanodac // = 15
}
public class HistoryRecord
{
public InstrType InstructionType { get; set; }
public HistoryRecord(InstrType instructionType)
{
//NOTE: Possible bug here
//We could possibly be missing this assignment perhaps:
//InstructionType = instructionType;
}
}
[TestClass]
public class UnitTest1
{
/// <summary>
/// This method should pass
/// </summary>
[TestMethod]
public void TestMethod1()
{
var myVal = InstrType.Nanodac;
Assert.AreEqual(InstrType.Nanodac, myVal);
}
/// <summary>
/// This method should fail with -> Expected:<Nanodac>. Actual:<HydraSbs>
/// </summary>
[TestMethod]
public void TestMethod2()
{
// Please check the 'HistoryRecord' class above for the possible error
// Here the the value of InstructionType has not actually been set yet, so will default to 0 in the underlying datatype (int)
// In this case that underlying 0 value will be mapped to the first enum value which is HydraSbs
// that is why you'd get the error -> Expected:<Nanodac>. Actual:<HydraSbs>
var historyRecord = new HistoryRecord(InstrType.Nanodac);
var myVal = historyRecord.InstructionType;
var intValue = (int)myVal;
Assert.AreEqual(0, intValue);
Assert.AreEqual(InstrType.Nanodac, myVal);
}
}
}
答案 2 :(得分:-2)
这只是一个建议,我会将两者都转换为 int ,然后进行比较。
以下是一个示例
Assert.AreEqual((int)myVal, (int)InstrType.Nanodac)
或者您可以将预期结果移到左侧,避免演员。
Assert.AreEqual(InstrType.Nanodac, myVal)
P.S。很高兴干净/重建工作。