Reputation:
Lets say I have this
public interface ISomeInterface
{
public string GetSomething();
}
public class Sample : ISomeInterface
{
public string GetSomething()
{
return "HELLO";
}
public string MethodToTest()
{
return GetSomething();
}
}
I need to mock
GetSomething()
in order to change string output of
MethodToTest()
So I did this:
var mockClientConfigExtensions = new Mock<ISomeInterface>();
mockClientConfigExtensions.Setup(ss => ss.GetSomething()).Returns("DDDD");
var _os = new Sample();
var k = _os.MethodToTest();
Assert.Equal("DDDD", k);
The problem is GetSomething()
still returns HELLO instead of mocking it. How do I mock GetSomething(); ?
Upvotes: 3
Views: 598
Reputation: 11871
Your mocked interface with the Setup is mockClientConfigExtensions
, but the instance you are testing, k
, is a concrete type and completely different to the one you performed a Setup on.
This is not how you should be mocking. Usually you would mock dependencies of the class under test and then perform setups on those.
If you really must mock the class under test, then you need to actually setup the methods on a concrete instance not on the interface. You also need to make the methods you want to mock virtual. e.g:
public class Sample : ISomeInterface
{
public virtual string GetSomething()
{
return "HELLO";
}
public string MethodToTest()
{
return GetSomething();
}
}
...
var mockSample = new Mock<Sample>();
mockSample.Setup(s => s.GetSomething()).Returns("mystring");
Assert.Equal("mystring", mockSample.Object.MethodToTest());
https://github.com/Moq/moq4/wiki/Quickstart
Upvotes: 5