Using Assert.AreSame

Just as an aside, Part 2 of my jQuery article is up.


I think this is something most people know, but wanted to throw it out there just in case. There are subtleties that should be understood when using Assert.AreSame(expected, actual) over other Asserts. AreSame does a reference check, which is often more telling and accurate than a value check. For example, given the following method which creates a new version of a User:

public User Version(string newName)
{
var newUser = this.Clone();
newUser.Name = newName;
newUser.Save();
return newUser;
}

The best way to verify that the newUser is returned is via Assert.AreSame:

[Test]
public void New_Version_Is_Returned()
{
var user = Partial<User>();
var clone = Partial<User>();
user.Stub(u => u.Clone()).Return(clone);
clone.Stub(c => c.Save());

Assert.AreSame(clone, user.Version(“newName”));
}


I find this particularly useful when dealing with collections. Rather than test that each item within the collection is as expected, simply test the collection itself:

[Test]
public void Found_Users_Are_Returned_From_Store()
{
var expected = new List<User>(0);
var store = Dynamic<IUserStore>();
store.Expect(s => s.FindUsers(null)).IgnoreArguments().Return(expected);

Assert.AreSame(expected, new Repository<User>().Find())
}


There’s no need to setup anything more complicated as our expected result. The focus of this test isn’t on whether the list of users is properly populated, but rather that the list of users is properly returned


Of course, using Assert.AreSame does add coupling between our test and our behavior. The above test will only work so-long as the Repository doesn’t do anything that changes the actual reference. If the Repository suddenly decided to return a new List as a means of making the original immutable, our test would fail. This isn’t necessary bad coupling because you SHOULD be testing for these types of details, but you do need to be aware of the different meanings and approached.

This entry was posted in Uncategorized. Bookmark the permalink. Follow any comments here with the RSS feed for this post.

Comments are closed.