我正在尝试创建RESTApi的单元测试但是当我尝试从控制器调用.Get {id}方法时出现错误。
(控制器被嘲笑,因为它是抽象的)
当我到达测试的最后一行时,我收到错误(标题中)。
(我已经尝试过Asserts和.Verify(),但是我没有联系到他们,因为我在到达之前就错了)
我觉得我错过了一些小事,但这又是我第一次和Moq在一起。
protected CustomActionModelController(IModelProvider<TModel> provider, IModelMapper mapper)
{
_mapper = mapper;
_provider = provider;
_customActions = new Dictionary<string, Func<string, object, object>>();
InitializeCustomActions();
}
protected abstract void InitializeCustomActions();
[HttpGet("{id}")]
[Produces(DefaultContentType)]
public virtual TDto Get([FromRoute]string Id)
{
return ToDto(_provider.Get(Id));
}
[TestMethod]
public void GetWithIdParameterReturnsSingleObject()
{
var provider = new Mock<IModelProvider<BaseDomainModel>>();
var mapper = new Mock<IModelMapper>();
var services = new Mock<IServiceCollection>();
var builder = new AutofacBuilder();
builder.RegisterType<IModelProvider<BaseDomainModel>, FakeDataProvider>().SingletonScope();
var customMock = new Mock<CustomActionModelController<BaseDomainModel, BaseObjectDto>>(provider.Object, mapper.Object);
customMock.Setup(x => x.Get(It.IsAny<string>())).Returns((BaseObjectDto s) => s = new BaseObjectDto("Test", "test"));
var actual = customMock.Object.Get("1");
}
答案 0 :(得分:0)
不要设置测试方法。在模拟中使用CallBase
var customMock = new Mock<CustomActionModelController<BaseDomainModel, BaseObjectDto>>(provider.Object, mapper.Object) {
// Whether the base member virtual implementation
// will be called for mocked classes if no setup is matched.
CallBase = true
};
var actual = customMock.Object.Get("1");