1

I am doing unit testing using NUnit and Moq framework. When I try to mock the IRepository using mockRepo.Setup(x=>x.GetStr(It.IsAny)()).Returns(str) then the method which is to be tested gets overridden inside Repository class and the build fails. But instead mocking the IRepository if I mock the Repository making the method which is to be tested as virtual then the data is getting mocked and the test runs.

Krits
  • 85
  • 9
  • 1
    Interface methods are implicitly virtual, in the sense that there's no way to specify an implementation. If a class method isn't virtual, then a subclass cannot replace the implementation. – Jeremy Lakeman Sep 29 '20 at 06:47
  • 1
    Why do you mock the method to be tested? You should mock the **dependencies**, not your **system under test**. – MakePeaceGreatAgain Sep 29 '20 at 07:23
  • @HimBromBeere thank you so much, I am trying it out this way now and pretty much succeeding. – Krits Sep 30 '20 at 12:08

1 Answers1

4

Any kind of mocking relies on members to be overridable. Your mocking-framework will create some class that either implements your interface or overrides your class. So what the framework creates is similar to the following:

class WeirdClassName : IRepository
{
    string GetString(object o) => "SomeString";
}

or if your member would be a class-member this:

class WeirdClassName : Repository
{
    string override GetString(object o) => "SomeString";
}

Interface-members are implictely overridable, as they literally do not provide any own logic. You can allways provide your own implementation for it. Class-members are only overridable, if they are virtual.

In your case there seems to be some difference in the test depending on if you mock the interface or the class. That probably indicates your test depends on some internals of the class - e.g. some initialization on the repo. You should either mock that also, or decouple your test from that dependency.

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
  • Thank you @HimBromBeere for the solution. I am now looking for mocking the dependency. And it is working. – Krits Sep 30 '20 at 12:11