3

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?

2
  • I'm not seeing what you mean, your edit is of type HttpStatusCodeResult and has statuscode 400 with no description, just as your result that you specify in your test. What's not working as it should? Or is your assert failing? in that case i'd say that the .Equals implementation from HttpStatusCodeResult is not dooing what you expect it to do Commented Apr 11, 2016 at 11:00
  • When I assert that edit and result are equal in my test that fails and I cant understand why. Commented Apr 11, 2016 at 11:01

2 Answers 2

4

Assert.AreEqual(a,b) is the same as Assert.IsTrue(Object.Equals(a,b))

HttpStatusCodeResult does not implement Equals so the call goes to the default Object.Equals() which in turn defaults to Object.RefrenceEquals(a,b))

If the current instance is a reference type, the Equals(Object) method tests for reference equality, and a call to the Equals(Object) method is equivalent to a call to the ReferenceEquals method. Reference equality means that the object variables that are compared refer to the same object.

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.