views:

57

answers:

2

//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);
   }

           }
A: 

Initialize your object properties with some values before checking if it exists.

 public ViewResult DoSometing()
   {
       Foo obj = new Foo();
       obj.Property1 = "some value";
       bool IsExist = _repository.IsExist(obj);
                   //IsExist always false,is it a bug?
       return View(foo);
   }
Marwan Aouida
interesting.thanks Marwan.
tobias
+1  A: 

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 foo that 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 the foo object). To be clearer, if you had this code:

Foo f1 = new Foo();
Foo f2 = new Foo();
repository.Expect(s => s.IsExist(f1)).Returns(true);
bool b1 = repository.Object.IsExist(f1);
bool b2 = repository.Object.IsExist(f2);

I would expect that b1 would be true (since that's the specific expectation you set up, i.e. given f1 return true) and b2 would be false (since you didn't tell the repository to do anything specific if it received f2, 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:

repository.Expect(s => s.IsExist(Arg<Foo>.Is.TypeOf)).Returns(true);

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:

repository.Expect(s => s.IsExist(f => f.SomeProperty == "blah" && f.OtherProperty.StartsWith("baz")))).Returns(true);

which would return true if foo.SomeProperty equaled "blah" and foo.OtherProperty started 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...

Alconja
u right.i mistaken.
tobias