Reputation: 2900
I have an API as below:
private readonly IMyService _myService;
public MyController(IMyService myService)
{
_myService = myService;
}
//GET: api/values
[HttpGet]
public MyOutput<MyEntity> Get(string f, string o)
{
var fItems = JsonConvert.DeserializeObject<Dictionary<string, string>>(f);
var oItems = GetDictionaryFromStr(o ?? "");
var myInput = new MyInput<MyEntity>()
{
PredicateDictionary = fItems,
OrderByDictionary = oItems
};
var result = _myService.Search(myInput);
return result;
}
It works well. Now, I want to write a unit test for my API, using Moq and Xunit;. I want to set the expected values of result, then mock my DIs and call the controller, What I expect is that the return value of controller and my results be equal. but I don't know why result in var result = api.Get(f, o);
is null after returns from controller. Is there anything wrong whit my test?
[Fact]
public void Should_ReturnResult_When_CallingMyApi()
{
//Arrange
var f = "{'Currency':'UR'}";
var o = "+Amount";
var fItems = JsonConvert.DeserializeObject<Dictionary<string, string>>(f);
var oItems = GetDictionaryFromStr(o ?? "");
var baseServiceMock = new Mock<IMyService>();
baseServiceMock
.Setup(x => x.Serach(It.Is<MyInput<MyEntity>>
(i => i.PredicateDictionary== fItems
&& i.OrderByDictionary == oItems
&& i.Paging == pagingItems
)))
.Returns(new MyOutput<MyEntity>()
{
OrderByDictionary = oItems,
PredicateDictionary = fItems
});
var api = new MyController(baseServiceMock.Object);
//Act
var result = api.Get(f, o);
////Assert
Assert.Equal(result.PredicateDictionary, fItems);
Assert.Equal(result.OrderByDictionary, oItems);
}
Update:
Also I changed the baseServiceMock
, with and without the It.Is
. In case of It.Is
I added
baseServiceMock
.Setup(x => x.Search(It.Is<MuInput<MyEntity>>
(i => i.PredicateDictionary.Keys == fItems.Keys
&& i.PredicateDictionary.Values == fItems.Values
&& i.OrderByDictionary.Keys == oItems.Keys
&& i.OrderByDictionary.Values == oItems.Values
&& i.Paging == pagingItems
)))
.Returns.....
Upvotes: 0
Views: 45
Reputation: 2900
The problem was comparing two objects in SetUp()
. So I Edited the code as below:
.Setup(x => x.Find(It.Is<MuInput<MyEntity>>
(i => i.PredicateDictionary.First().Key == "Currency"
&& i.PredicateDictionary.First().Value == "CU_UR"
&& i.OrderByDictionary.First().Key == "Amount"
&& i.OrderByDictionary.First().Value == "Asc")))
Upvotes: 1