[英]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.