I’m trying to learn how to do Unit testing with C# and Moq, and I’ve built a little test situation. Given this code:
public interface IUser
{
int CalculateAge();
DateTime DateOfBirth { get; set; }
string Name { get; set; }
}
public class User : IUser
{
public DateTime DateOfBirth { get; set; }
string Name { get; set; }
public int CalculateAge()
{
return DateTime.Now.Year - DateOfBirth.Year;
}
}
I want to test the method CalculateAge(). To do this, I thought I should try giving a default value to the DateOfBirth property by doing this in my test method:
var userMock = new Mock<IUser>();
userMock.SetupProperty(u => u.DateOfBirth, new DateTime(1990, 3, 25)); //Is this supposed to give a default value for the property DateOfBirth ?
Assert.AreEqual(22, userMock.Object.CalculateAge());
But when It comes to the assertion, the value of CalculateAge() equals 0, although DateOfBirth equals new DateTime(1990, 3, 25).
I know this may look like a silly example, but whatever… I thought I could use mocking to give values to not-yet-developed method/properties in my objects, so the testing of a method wouldn’t depend on another component of my class, or even setting up a default context for my object (hence the name of the user here…) Am I approaching this problem the wrong way?
Thanks.
Yes, you approaching it wrong, but don’t worry, I’ll explain why. First hint would be
When you are doing:
You just creating a fake\mock object of that interface, that has nothing to do with your initial
Userclass, so it doesn’t have any implementation ofCalculateAgemethod, except of fake one that just silly returns 0. That’s why you are getting 0 in your assert statement.So, you were saying:
You could, let’s say you will have some consumer of your IUser, lets say like the following:
in that case mocking of IUser will make total sense, since you want to test how your
ConsumerOfIUserbehaves when IUser.CalculateAge() returns 10. You would do the following: