Mocking an NHibernate ISession with Moq

后端 未结 2 1984
情书的邮戳
情书的邮戳 2020-12-08 19:52

I am starting a new project with NHibernate, ASP.NET MVC 2.0 and StructureMap and using NUnit and Moq for testing. For each of my controllers I have a single public construc

相关标签:
2条回答
  • 2020-12-08 20:22

    Below is the solution I came up with which seems to work perfectly. Again, I am not testing NHibernate and I am not testing the database - I simply want to test the controllers which depend on NHibernate. The issue with the initial solution appears to be the fact that I was calling a Method as well as reading the List member of the session in the MOQ setup call. I broke up these calls by breaking the solution into a QueryMock and a Session Mock (create query returns an IQuery object). A transaction mock was also necessary as it is a dependency (in my case) of the session...

            [Test]
            public void DummyTest()
            {
                var userList = new List<User>() { new User() { ID = 2, FirstName = "John", LastName = "Peterson" } };
                var sessionMock = new Mock<ISession>();
                var queryMock = new Mock<IQuery>();
                var transactionMock = new Mock<ITransaction>();
    
                sessionMock.SetupGet(x => x.Transaction).Returns(transactionMock.Object);
                sessionMock.Setup(session => session.CreateQuery("from User")).Returns(queryMock.Object);
                queryMock.Setup(x => x.List<User>()).Returns(userList);
    
                var controller = new UsersController(sessionMock.Object);
                var result = controller.Index() as ViewResult;
                Assert.IsNotNull(result.ViewData);
            }
    
    0 讨论(0)
  • 2020-12-08 20:47

    Rather than mocking the Session, one might consider setting up a different Configuration for unit-tests. This unit-testing Configuration uses a fast, in-process database like SQLite or Firebird. In the fixture setup, you create a new test database completely from scratch, run the scripts to set up the tables, and create a set of initial records. In the per-test setup, you open a transaction and in the post-test teardown, you rollback the transaction to restore the database to its previous state. In a sense, you are not mocking the Session, because that gets tricky, but you are mocking the actual database.

    0 讨论(0)
提交回复
热议问题