Im doing integration testing on my rest web api. I have the following setup :
public ItemsControllerTests()
{
this.itemFetcher = new Mock<IItemFetcher>();
this.itemFetcher.Setup(sp => sp.GetItems(It.IsAny<string>()))
.Returns(Task.FromResult(
(200, new Response<ICollection<Item>>()
{
Data = new List<Item>()
{
new Item()
{
Id = 42,
Artwork = "http://cdn.fake.com/fake.png",
Category = new Category()
{
Id = 2,
Name = "musical"
},
Name = "Awesome bagpipe"
}
},
Error = null
})
));
client = new TestServer(new WebHostBuilder()
.ConfigureServices(services =>
{
//Middlewares
services.AddSingleton<IItemFetcher, ItemFetcher>();
services.AddCarter();
})
.Configure(app => { app.UseCarter(); })
).CreateClient();
}
[Fact]
public async void GetItemsOK()
{
response = client.GetAsync("/items").GetAwaiter().GetResult();
var content = await response.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
which works perfectly fine. the problem is its actually doing a REAL request as its using the real class. So my doubt is in this line :
services.AddSingleton<IItemFetcher, ItemFetcher>();
How can I use my mock object this.itemFetcher = new Mock(); instead of the real one. If I try this :
services.AddSingleton<IItemFetcher, itemFetcher>();
It fails as I am actually using an instance of a class instead of a class.
How can I overcome this?
ok. got it. You simply do it like this :
services.AddSingleton(itemFetcher);