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.
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.