单元测试ApiController使用autoinclude获取实体

时间:2016-05-23 11:47:27

标签: c# entity-framework unit-testing

我的实体中有很多关系,我正在尝试测试我的ApiController以给我正确的结果。我检查确定是否给出了Id,返回正确的结果。在这个实体中有一个ICollection列表,我试图让AutoInclude获取它的结果。

在我的单元测试中,我设置了所需的模型并手动创建对象。但是,当我获取我想要的对象时,AutoInclude属性失败,我从我的存储库中得到一个null。

控制器的实际使用情况有效,但单位测试却没有。我不知道我在这里错过了什么或做错了什么。

我的代码:

单元测试

    [TestMethod]
    public void UpdateDashboardScreen_OkResult()
    {
        // Arrange
        _unitOfWorkMock.Setup(
            p => p.Repository<DashboardScreen>().Get(It.IsAny<Expression<Func<DashboardScreen, bool>>>()))
            .Returns(_listOfDashboardScreens.Find(a => a.Id.Equals(_testDashboardScreen1.Id)));

        _unitOfWorkMock.Setup(p => p.UserRepository().GetAllActive(It.IsAny<Expression<Func<User, bool>>>()))
            .Returns(_listOfUsers);

        var dto = new DashboardScreenDto
        {
            Id = _testDashboardScreen1.Id,
            Title = _testDashboardScreen1.Title,
            DataType = (int) _testDashboardScreen1.DataType,
            Type = (int) _testDashboardScreen1.Type,
            Visible = _testDashboardScreen1.Visible,
            IsRemoved = _testDashboardScreen1.IsRemoved,
            Users = new List<string> {_testUser.Id}
        };

        // Act
        var actionResult = _dashboardScreenController.PostUpdatedScreen(dto);

        // Assert
        Assert.IsInstanceOfType(actionResult, typeof (OkResult));
        _unitOfWorkMock.Verify(a => a.SaveChanges(), Times.Exactly(1));
    }

实体

public class DashboardScreen : BaseEntity
{
    [Range(0, int.MaxValue)]
    public int Id { get; set; }

    [Required]
    [StringLength(100, 
        ErrorMessage = "Title can not be longer than 100 characters.")]
    [RegularExpression(@"^(\w{0,22}(\s|\b))+$", 
        ErrorMessage = "A word may not be longer than 22 characters.")]
    public string Title { get; set; }

    [EnumDataType(typeof(DashboardType))]
    public DashboardType Type { get; set; }

    [EnumDataType(typeof(DashboardDataType))]
    public DashboardDataType DataType { get; set; }

    [Required]
    public bool Visible { get; set; }

    public string Data { get; set; }

    public virtual ICollection<User> AllocatedUsers { get; set; }
}

控制器

// TODO: Fix unit tests so that the include works. Removing the include here makes the Unit Tests succeed.
var original = _uow.Repository<DashboardScreen>().Get(t => t.Id == slDto.Id, "AllocatedUsers");
if (original == null)
{
    return NotFound();
}

0 个答案:

没有答案