Moq:Mock SetUp方法仅在测试期间返回null

时间:2016-01-14 02:01:13

标签: c# entity-framework unit-testing mocking moq

我刚刚将依赖注入添加到我的应用程序中,并希望对我的方法运行模拟测试以确保它们正常工作。

我有一个域类Person,其中包含以下属性:

public class Person : DomainBase
{
   public string FirstName { get; set; }
    public string LastName { get; set; }
    public char Gender { get; set; }
    public DateTime DOB {get; set; }
}

我有一个与其他域名管理员共享的部分manager课程:

public partial class Manager : IManager1
{
    private IHiveTiesContext _ctx; 
    public Manager(IHiveTiesContext context)
    {
        _ctx = context;
    }
}

接口IManager1是从我的PersonManager类中提取的,包含所有需要的方法。

正在调用并测试我的PersonManager CreatePerson()方法:

public partial class Manager : IManager1
{
    public Person CreatePerson(string fn, string ln, DateTime dob, char gender, Guid RId)
    {
       var _person =_ctx.People.Add(new Person
       {  
          FirstName = fn,
          LastName = ln,
          DOB = dob,
          Gender = gender,
          RowId = RId});

          _ctx.SaveChanges();
          return _person;
        }
    }  
} 

接下来我的上下文再一次从中提取了一个接口IHiveTiesContext

public class HiveTiesContext : DbContext, IHiveTiesContext
{
    public HiveTiesContext() :  base("hiveties")
    {
        Database.SetInitializer<HiveTiesContext>(null);
    }

    public virtual IDbSet<Person> People { get; set; }
}

最后,我试图像这样测试CreatePerson

public class PersonManagerMockTest
{
    private static Guid personGuid;

    [ClassInitialize]
    public static void Init(TestContext test)
    {
        personGuid = Guid.NewGuid();
    }

    [TestMethod]
    public void AddNewPerson()
    {
        //Arrange
        var mockDbSet = new Mock<DbSet<Person>>();

        var mockContext = new Mock<IHiveTiesContext>();
        mockContext.Setup(x => x.People)
            .Returns(mockDbSet.Object);

        var manager = new Manager(mockContext.Object);

        //Assert
        var _person = manager.CreatePerson("Winston", "Gabriel", DateTime.Now, 'M', personGuid);

        if(_person == null)
        {
            throw new Exception("NOT WORKING MAN!!!!");
        }

        var personid = mockContext.Object.People.Single(x => x.RowId == personGuid).Id;

        //Act
        mockDbSet.Verify(x => x.Add(It.IsAny<Person>()));
        mockContext.Verify(x => x.SaveChanges());
    }
}

我的问题是我的Person对象永远不会被创建,也就是说,它总是返回一个null值,并且总是抛出异常。我相信我告诉它返回一个Person实体,但我不确定我哪里出错了。这是我第一次使用Moq并运行Mock Unit Tests

我感谢任何建议。谢谢。

2 个答案:

答案 0 :(得分:7)

您没有在Add的{​​{1}}方法上设置任何行为。

添加:(此行初始化方法以返回给定的人)

mockDbSet

在嘲笑之间:

mockDbSet.Setup(x => x.Add(It.IsAny<Person>()))
         .Returns <Person>(p => p);

答案 1 :(得分:1)

我在IHiveTiesContext中创建了一个新的签名/函数来保存Person对象。 (现在由你来决定如何实现界面)。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SampleManager
{
    public class Manager : IManager
    {
        private IHiveTiesContext _ctx;
        public Manager(IHiveTiesContext context)
        {
            _ctx = context;
        }

        public Person CreatePerson(string fn, string ln, DateTime dob, char gender, Guid RId)
        {
            var person = _ctx.Save(fn, ln);
            return person;
        }
    }


    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public char Gender { get; set; }
        public DateTime DOB { get; set; }
        public Guid RowId { get; set; }
    }

    public interface IManager
    {
        Person CreatePerson(string fn, string ln, DateTime dob, char gender, Guid RId);
    }

    public interface IHiveTiesContext
    {
        Person Save(string fn, string ln);
    }
}

/// <summary>
    ///A test for CreatePerson
    ///</summary>
    [TestMethod()]
    public void CreatePersonTest1()
    {
        var mock = new Mock<IHiveTiesContext>();
        //fill up your expected object
        mock.Setup(m => m.Save(It.IsAny<string>(), It.IsAny<string>())).Returns(new Person { FirstName = "William" });

        Manager t = new Manager(mock.Object);
        var results = t.CreatePerson(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<DateTime>(), It.IsAny<Char>(), It.IsAny<Guid>());

        Assert.AreEqual("William", results.FirstName);
    }