[英]How can I use Mock to test my controller?
I have a controller: 我有一个控制器:
public class SelectController : Controller {
private readonly IChartService _chartService;
private readonly IProductService _productService;
private readonly IStoreService _storeService;
public SelectController ( IChartService chartService,
IProductService productService,
IStoreService storeService ) {
_chartService = chartService;
_productService = productService;
_storeService = storeService;
}
[HttpGet]
[Route( "stores" )]
public Task<IEnumerable<IStore>> GetStoresInfo ( string encryptedUserId ) {
return _storeService.GetStoresInfo( EncryptionProvider.Decrypt( encryptedUserId ) );
}
}
I am trying to test GetStoresInfo
using Moq. 我正在尝试使用Moq测试
GetStoresInfo
。 This is all I have so far: 到目前为止,这就是我所拥有的:
[Fact]
public class Controller_Returns_List_Of_Stores()
{
//Arrange
var mockStoreService = new Mock<IStoreService>();
var mockChartService = new Mock<IChartService>();
var mockProductService = new Mock<IProductService>();
var controller = new SelectController(mockChartService, mockProductService, mockStoreService);
//Act
//Assert
}
The new SelectController
wont accept the 3 objects I am passing in due to being unable to convert from InService
to InService
. 新
SelectController
不会接受3个对象,我在路过由于暂时无法从转换InService
到InService
。 Am I meant to be doing some more setup? 我是否打算进行更多设置? Or is it something to do with the return type being a Task?
还是与返回类型为Task有关?
Any help much appreciated. 任何帮助,不胜感激。
Call .Object
on the mocks to pass the mocked objects. 在模拟对象上调用
.Object
以传递模拟对象。
var controller = new SelectController(
mockChartService.Object,
mockProductService.Object,
mockStoreService.Object
);
You also need to setup the mock object's behavior so that they function as expected when invoked. 您还需要设置模拟对象的行为,以使它们在被调用时能够按预期运行。
IEnumerable<IStore> fakeData = new List<IStore>();
mockStoreService
.Setup(_ => _.GetStoresInfo(It.IsAny<string>()))
.Returns(Task.FromResult<IEnumerable<IStore>>(fakeData));
Reference Moq Quickstart to get a better understanding of how to use the mocking framework. 参考Moq快速入门 ,以更好地了解如何使用模拟框架。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.