15

The original method it still called when i try to use Moq. Here is my code:

var mockedBetRepository = new Mock<BetRepository>(new FakeSiteContext());
mockedBetRepository.CallBase = true;
Bet bet = new Bet();
mockedBetRepository.Setup<Bet>(m => m.UpdateBet(bet)).Returns(bet);

betRepository = mockedBetRepository.Object;

Later in the code, betRepository.UpdateBet(bet) is called, but its not my mocked method which gets called, instead, the class's method gets called:

public virtual Bet UpdateBet(Bet betToUpdate)
{
    siteContext.Entry(betToUpdate).State = System.Data.EntityState.Modified;
    siteContext.SaveChanges();
    return betToUpdate;
}

Why it this happening?

2 Answers 2

13

I have found the problem.

If i replace

Bet bet = new Bet();
mockedBetRepository.Setup<Bet>(m => m.UpdateBet(bet)).Returns(bet);

with this

mockedBetRepository.Setup<Bet>(m => m.UpdateBet(It.IsAny<Bet>())).Returns((Bet b) => b);

Then it works.

3
  • 1
    Are you using the same reference when you Setup the method as you do when it's actually called? Is so that would explain the behavior you were seeing, as Moq can be used to test that specific values were used when Verifying. For reference types, that would be specific instances of your object.
    – Andy
    Feb 7, 2012 at 18:16
  • Yeah, that was probably it. Didn't know the mocks were so exclusive and explicit.
    – ErikTJ
    Feb 7, 2012 at 18:42
  • why we should use It.IsAny<Bet>() instead of writing a method.
    – Jeeva J
    Feb 21, 2020 at 2:56
0

Your setting callbase to true, which will call your actual implementation.

4
  • Yes, it will call the base implementation "if no setups it matched", which what i can see, there is?
    – ErikTJ
    Feb 6, 2012 at 10:11
  • @ErikTJ And did you try it without CallBase = true?
    – Andy
    Feb 6, 2012 at 16:23
  • I have found the solution, see my answer. Also setting CallBase = false is not possible since i need just to mock one method of many.
    – ErikTJ
    Feb 6, 2012 at 16:39
  • @ErikTJ You asked "why is this happening" and I explained why it was happening. I wasn't suggesting you set CallBase to false.
    – Andy
    Mar 28, 2013 at 17:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.