//IsExist always false,is it a bug?
[TestMethod]
public void IsExist()
{
private Mock<IRepository> repository = new Mock<IRepository>();
Foo f = new Foo();
repository.Expect(s => s.IsExist(foo)).Returns(true);
var controller = new MyController(repository.Object);
var result = (ViewResult)controller.DoSometing();
}
public class MyController : Controller
{
IRepository _repository ;
public MyController(IRepository repository)
{
_repository = repository;
}
public ViewResult DoSometing()
{
bool IsExist = _repository.IsExist(new Foo());
//IsExist always false,is it a bug?
return View(foo);
}
}
Firstly, which mocking library are you using (the answer may change based on that)?
I know if you were using Rhino Mocks, the problem would be that your expectation is set up to return true when it receives that specific instance of
foothat you create at the top. This is a different instance to what is being passed in when its executed in your controller, so it returns false (since no expectation was set against that version of thefooobject). To be clearer, if you had this code:I would expect that
b1would be true (since that’s the specific expectation you set up, i.e. givenf1returntrue) andb2would be false (since you didn’t tell the repository to do anything specific if it receivedf2, so it will fall back to its default behaviour of returning false).In Rhino Mocks, you’d need to set up your expectation like this:
which would return true if IsExist was called with any instance of a Foo object. If you needed to be more specific, you could have something like this:
which would return true if
foo.SomePropertyequaled"blah"andfoo.OtherPropertystarted with"baz".Doesn’t look like you’re using Rhino Mocks, as your syntax is a little different, but hopefully that points you in the right direction…