我有一個調用另一個api服務的api服務。當我設置了模擬對象,它失敗,出現錯誤:表達式引用不屬於模擬對象的方法
NotSupportedException: expression references a method that does not belong to the mocked object.
這是代碼:
private Mock<IEnumerable<ICarrierApiService<AccountSearchModel>>> _mockCarrierService;
private Mock<IApiService<AccountSearchModel>> _mockApiService;
[SetUp]
public void SetUp()
{
_mockApiService = new Mock<IApiService<AccountSearchModel>>();
_mockCarrierService = new Mock<IEnumerable<ICarrierApiService<AccountSearchModel>>>();
_mockApiService.Setup(x => x.GetFromApiWithQuery(It.IsAny<string>())).Returns(ApiValue());
// Error occurred when call _mockApiService.GetFromApiWithQuery() in .Select()
_mockCarrierService.Setup(x => x
.Select(s => s
.GetFromApiWithQuery(It.IsAny<string>())).ToList())
.Returns(new List<IQueryable<AccountSearchModel>> { ApiValue() });
}
我讀Expression testing with Moq但它並沒有對我的情況下工作。如果我刪除了這個_mockCarrierService.Setup()
,則測試用例可以運行,但由於沒有設置有效的List<IQueryable<AccountSearchModel>>
而導致NullReferenceException
失敗。
任何想法如何我可以實現這一目標?
腳註:當前解決方案
FWIW,下面是我目前使用的解決方案。 我很樂意爲這個問題提供更好的方法(直到Moq開始支持嘲笑擴展方法)。
private List<ICarrierApiService<AccountSearchModel>> _mockCarrierService;
private AccountSearchController _mockController;
private Mock<ICarrierApiService<AccountSearchModel>> _mockApiService;
[SetUp]
public void SetUp()
{
_mockApiService = new Mock<ICarrierApiService<AccountSearchModel>>();
_carrierServiceMocks = new List<ICarrierApiService<AccountSearchModel>> { _mockApiService.Object };
_mockApiService.Setup(x => x.GetFromApiWithQuery(It.IsAny<string>())).Returns(ApiValue());
_mockController = new AccountSearchController(_carrierServiceMocks);
}
腳註:替代模擬框架
我還發現一個商業嘲弄的框架,支持嘲諷擴展方法,並鏈接到如何對文檔:Telerik JustMock。
感謝您的幫助。我從這裏提到的那個作者那裏找到了另一篇文章。如果我添加更復雜的[Fact]方法,它可能會起作用。我必須嘗試去確認。 – 2014-12-04 12:14:01
@IsabelHM,我更新了答案,所以你可能會從不同的角度考慮問題:) – 2014-12-11 15:55:12
謝謝你的信息。 – 2014-12-16 22:05:26