haddow64 haddow64 - 3 months ago 25
ASP.NET (C#) Question

UnitTest on MVC controller HttpStatusCode not equal

I'm doing a unit test on a simple controller checking that when a null ID is passed in that it returns a 400 code. However when I test this the result does not come back as being equal to a 400 error code.

My code:

int? nullID = null;
var edit = controller.Edit(nullID) as ActionResult;

var result = new HttpStatusCodeResult(400, null);

Assert.AreEqual(edit, result);


When I debug the test I get the expected result seen here:

Edit Result:

Edit Result

Expected Result:

Expected Result

Where am I going wrong on this?

Answer

I think that the equals method of HttpStatusCodeResult is looking at the reference key, i tested your setup and my assert fails as well. Asserting the statuscodes itself however does work. see example:

[TestMethod]
public void Test()
{

  var resultOne = new HttpStatusCodeResult(400, null);
  var resultTwo = new HttpStatusCodeResult(400, null);

  // Assert
  Assert.AreEqual(resultOne.StatusCode, resultTwo.StatusCode);

  Assert.AreEqual(resultOne, resultTwo);
}

The Assert.AreEqual(resultOne.StatusCode, resultTwo.StatusCode); succeeds while the Assert.AreEqual(resultOne, resultTwo); fails

update

See the MSDN page about HttpStatusCodeResult here you can see that the equals implemenation is Inherited from Object and therefor does not anything with the properties in the object, but only looks at the reference keys