单元测试期间Assert.AreEqual失败

时间:2015-05-22 12:48:58

标签: c# unit-testing

我正在为一个简单的控制台游戏项目运行以下测试,该项目正在使用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)方法,该方法然后调用以下代码并根据字符串返回枚举。

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 expected显示我的2个CommandAction属性为;命令:GoNorth和RelatedObject null

我的测试对象显示为;命令:GoNorth和RelatedObject:null

所以我的价值看起来是正确的,但我不知道为什么测试失败了?

4 个答案:

答案 0 :(得分:2)

您的.Equals()类型没有自定义CommandAction,因此AreEqual()正在对expected对象与Translate对象创建的对象进行参考比较1}}。它们是不同的实例,所以不相等。测试正确失败。

答案 1 :(得分:2)

该方法返回的对象不同。

检查正在进行参考比较并正确地告诉您它不是同一个对象。

答案 2 :(得分:1)

您的expected CommandAction不为空,但Translate正在返回null

也许您打算从CommandAction返回Translate

答案 3 :(得分:1)

Equals是参考类型。除非您覆盖Assert.AreEqual方法Assert.AreEqual(CommandEnum.GoNorth, ogbjecUndertest.Command); Assert.IsNull(ogbjecUndertest.RelatedObject); ,否则将检查引用相等性。由于您在方法中使用new关键字创建实例,因此它们将不相同。

如果您不想仅为单元测试实现相等性,则可以检查属性的值。

ogbjecUndertest.ShouldBeEquivalentTo(expected);

如果你可以使用Fluent Assertions,那么ShouldBeEquivalentTo()方法可以完成这项工作:

Application.Hwnd
相关问题