我有一个API如下:
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;
}
效果很好。现在,我想使用 Moq 和 Xunit ;为我的API编写单元测试。我想设置结果的期望值,然后模拟我的DI并调用控制器,我期望控制器的返回值和我的结果相等。但是从控制器返回后我不知道为什么var result = api.Get(f, o);
的结果为空。我的测试有什么问题吗?
[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);
}
更新
此外,我更改了baseServiceMock
,包括It.Is
。如果It.Is
我添加了
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.....
答案 0 :(得分:1)
问题是比较SetUp()
中的两个对象。所以我编写了如下代码:
.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")))