-
-
Notifications
You must be signed in to change notification settings - Fork 794
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Mock Object Won't Return an int (i.e. Value Type) #616
Comments
You've got a typo:
should be: Assert.Equal(45, await mockRepo2.Object.MethodAsync(42));
// ^ |
Thank you, I thought I was getting the same error because of a possible bug, but I see it was a mistake in my example. So I went back and looked at what I was actually doing and realized that my example was using a Value type and not a class, and my original code is using two separate instances of the same class, and I did not override the Equals method. Thx. public class UnitTest1
{
[Fact]
public async Task Test1()
{
var mockRepo1 = new Mock<IToBeTested>();
mockRepo1.Setup(r => r.MethodAsync(null)).ReturnsAsync(45);
var result1 = await mockRepo1.Object.MethodAsync(null);
Assert.Equal(45, result1);//Good
var testinstance = new TestClass
{
Id = 0,
DisplayName = "Display",
};
var mockRepo3 = new Mock<IToBeTested>();
mockRepo3.Setup(r => r.MethodAsync(testinstance)).ReturnsAsync(45);
var result3 = await mockRepo3.Object.MethodAsync(testinstance);//Good
//I just get a zero returned.
Assert.Equal(45, result3);
var mockRepo2 = new Mock<IToBeTested>();
mockRepo2.Setup(r => r.MethodAsync(new TestClass
{
Id = 0,
DisplayName = "Display",
})).ReturnsAsync(45);
var result2 = await mockRepo2.Object.MethodAsync(new TestClass
{
Id = 0,
DisplayName = "Display",
});
Assert.Equal(45, result2);//Only works if Equals is overridden
}
public interface IToBeTested
{
Task<int> MethodAsync(object input);
}
class TestClass
{
public int Id { get; set; }
public string Name { get; set; }
public string DisplayName { get; set; }
public override bool Equals(object obj)
{
var input = obj as TestClass;
if (input != null)
return Id == input.Id && Name == input.Name && DisplayName == input.DisplayName;
else
return false;
}
//public override int GetHashCode()
//{
// return Id.GetHashCode() ^ Name.GetHashCode() ^ DisplayName.GetHashCode();
//}
}
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
When setting up a method in the interface to return an int, I just get a zero (default int).
The text was updated successfully, but these errors were encountered: