为什么单元测试模拟控制器总是空的

why unit test mocks always null with controller

想单元测试使用模拟我的数据实际上是存储在内存中的,为什么总是从控制器响应结果中得到null

这是我的控制器

private readonly IUnitOfWorkAsync _unitOfWorkAsync;
        private readonly IVersionService _versionService;
        public VersionController(IUnitOfWorkAsync unitOfWorkAsync, IVersionService versionService)
        {
            this._unitOfWorkAsync = unitOfWorkAsync;
            this._versionService = versionService;
        }


        public ActionResult Index()
        {
            var versions =  _versionService.Queryable();
            return View(versions);
        }

这是我的单元测试代码:

private Mock<IVersionService> _versionServiceMock;
        private Mock<IUnitOfWorkAsync> _unitOfWorkAsync;

        VersionController objController;
        List<Model.Models.Version> listVersion;

        [TestInitialize]
        public void Initialize()
        {

            _versionServiceMock = new Mock<IVersionService>();
            _unitOfWorkAsync = new Mock<IUnitOfWorkAsync>();
            objController = new VersionController(_unitOfWorkAsync.Object, _versionServiceMock.Object);

            listVersion = new List<Model.Models.Version>() {
             new Model.Models.Version() { AppName="App 1",ObjectState=ObjectState.Added,AuditField=new AuditFields()},
             new Model.Models.Version() { AppName="App 2",AppVersion="1.0",ObjectState=ObjectState.Added,AuditField=new AuditFields()},
             new Model.Models.Version() { AppName="App 3",ObjectState=ObjectState.Added,AuditField=new AuditFields()}
            };
        }

        [TestMethod]
        public void Version_Get_All()
        {
            //Arrange
            _versionServiceMock.Setup(x => x.Query().Select()).Returns(listVersion);

            //Act
            var result = (( objController.Index() as ViewResult).Model) as List<Model.Models.Version>;


        }

为什么结果总是为null,如何检查为什么为null。

注意:我在我的项目控制器中使用 this 模式。

Moq 在模拟时创建它自己的接口实现。默认情况下,模拟接口上的所有方法都将 return null。

尝试模拟 _versionService.Queryable()。像这样:

[TestMethod]
public void Version_Get_All()
{
     //Arrange
    _versionServiceMock.Setup(x => x.Queryable()).Returns(listVersion);

     //Act
    var result = (( objController.Index() as ViewResult).Model) as List<Model.Models.Version>;


}