[英]Assert.AreEqual failed during unit test
我正在为一个正在运行的简单控制台游戏项目运行以下测试,该项目因Assert.AreEqual失败而失败。
[TestMethod]
public void TestMethod1()
{
//Arrange
CommandInterpreter interpreter = new CommandInterpreter(new List<IDungeonObject>());
CommandAction commandAction = new CommandAction(CommandEnum.GoNorth, null);
const string north = "Go North";
var expected = commandAction;
//Act
var ogbjecUndertest = interpreter.Translate(north);
//Assert
Assert.AreEqual(expected, ogbjecUndertest);
}
基本上,测试将一个字符串(在本例中为北)传递给Translate(north)方法,然后该方法调用以下代码并根据该字符串返回一个Enum。
public CommandAction Translate(string issuedCommand) // <-- Go North
{
if (issuedCommand.IndexOf(' ') == -1)
throw new InvalidCommandException("No command entered");
if (issuedCommand.Equals("Go South", StringComparison.OrdinalIgnoreCase))
return new CommandAction(CommandEnum.GoSouth, null);
if (issuedCommand.Equals("Go North", StringComparison.OrdinalIgnoreCase))
return new CommandAction(CommandEnum.GoNorth, null);
return null;
该方法接受以下命令的CommandAction类:
public class CommandAction
{
#region Properites
/// <summary>
/// Defines a valid commands
/// </summary>
public CommandEnum Command { get; private set; }
/// <summary>
/// Defines a dungeon object
/// </summary>
public IDungeonObject RelatedObject { get; private set; }
#endregion
#region Constructor
/// <summary>
/// User input action passed in by the dugeon controller
/// </summary>
/// <param name="command"></param>
/// <param name="dungeonObject"></param>
public CommandAction(CommandEnum command, IDungeonObject dungeonObject)
{
Command = command;
RelatedObject = dungeonObject;
}
#endregion
}
当我调试测试时,Assert期望将我的2 CommandAction属性显示为: 命令:GoNorth和RelatedObject null
我的测试对象显示为: 命令:GoNorth和RelatedObject:空
所以我的值看起来正确,但是我不知道为什么测试失败了?
您没有为CommandAction
类型定制的.Equals()
,因此AreEqual()
在expected
对象与Translate
创建的新对象之间进行引用比较。 它们是不同的实例,所以不相等。 测试正确失败。
该方法返回的对象不是同一对象。
该检查正在进行参考比较,并正确告诉您它不是同一对象。
您expected
CommandAction
不为null,但Translate
返回null
。
也许您打算从Translate
返回CommandAction
?
CommandAction
是引用类型。 除非您重写Equals
方法,否则Assert.AreEqual
将检查引用是否相等。 由于您要在方法内部使用new关键字创建实例,因此它们将是不同的。
如果您不想仅为单元测试实现相等性,则可以检查属性的值。
Assert.AreEqual(CommandEnum.GoNorth, ogbjecUndertest.Command);
Assert.IsNull(ogbjecUndertest.RelatedObject);
如果可以使用Fluent Assertions ,则ShouldBeEquivalentTo()方法可以完成以下工作:
ogbjecUndertest.ShouldBeEquivalentTo(expected);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.