Reputation: 378
I have the following interfaces and service implemented like this:
public interface IParentInterface<T> where T : class
{
T GetParent(T something);
}
public interface IChildInterface : IParentInterface<string>
{
string GetChild();
}
public class MyService
{
private readonly IChildInterface _childInterface;
public MyService(IChildInterface childInterface)
{
_childInterface = childInterface;
}
public string DoWork()
{
return _childInterface.GetParent("it works");
}
}
Here is my test for the DoWork method of MyService class:
[Fact]
public void Test1()
{
var mockInterface = new Mock<IChildInterface>();
mockInterface
.As<IParentInterface<string>>()
.Setup(r => r.GetParent("something"))
.Returns("It really works with something!");
var service = new MyService(mockInterface.Object);
string resp = service.DoWork(); // expects resp = "It really works with something!" but it's null
Assert.NotNull(resp);
}
Other info:
Upvotes: 2
Views: 1497
Reputation: 119156
Your mock setup is saying to mock the method with "something"
is passed in. You should change that to match what the class is passing in, e.g. "it works"
or much easier is to allow any string using It.IsAny<string>()
. For example:
mockInterface
.As<IParentInterface<string>>()
.Setup(r => r.GetParent(It.IsAny<string>()))
.Returns("It really works with something!");
Upvotes: 5