单元测试存储库模式中的测试服务实体框架代码优先

时间:2017-04-20 11:01:11

标签: c# entity-framework unit-testing unity-container unit-of-work

我正在尝试使用Moq和NUnit为服务设置单元测试。我尝试像这样嘲笑DbContextDbSet

 var mockSet = new Mock<DbSet<Student>>();
 var mockContext = new Mock<Context>();
 mockContext.SetupGet(m => m.Student).Returns(mockSet.Object)

但我的服务依赖于其他服务,所以我在[Setup]方法中尝试TestInit,但是当我尝试测试服务时,我得到了一个异常

  

非虚拟(VB中可覆盖)成员的设置无效:m =&gt; m.Student

我需要一个解决方案来在单元测试中注册我的服务和统一性

// This is how my whole code looks like
[TestClass]
public class StudentServiceTest
{
        private IComService _mockComService;
        private IAccountService _mockAccountService;

        protected MRContext Context;
 
        private IUnitOfWork _mockUnitWork;
 
        [SetUp]
        public void TestInit(MRContext context, IAccountService accountService, IComService comService, IUnitOfWork unitOfWork)
        {

            this._mockComService = comService;
            _mockUnitWork = unitOfWork;
            this._mockAccountService = accountService;
            Context = context;
 
        }
 
        [TestInitialize]
        public void Initialize()
        {
            var mockSet = new Mock&lt;DbSet&lt;Student>>();
            var mockContext = new Mock&lt;Context>();
            mockContext.SetupGet(m => m.Student).Returns(mockSet.Object);
        }

        [TestMethod]
        public void AutoAssignmentCases()
        {
            var service = new StudentService(_mockAccountService, _mockComService, _mockUnitWork);
            var students = service.DoSomeTask();
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsFalse(students.Any(c => !c.SubjectId.HasValue));
        }
    }

0 个答案:

没有答案