How are people unit testing with Entity Framework 6, should you bother?

前端 未结 11 1994

I am just starting out with Unit testings and TDD in general. I have dabbled before but now I am determined to add it to my workflow and write better software.

I ask

11条回答
  •  心在旅途
    2020-11-28 17:57

    I have fumbled around sometime to reach these considerations:

    1- If my application access the database, why the test should not? What if there is something wrong with data access? The tests must know it beforehand and alert myself about the problem.

    2- The Repository Pattern is somewhat hard and time consuming.

    So I came up with this approach, that I don't think is the best, but fulfilled my expectations:

    Use TransactionScope in the tests methods to avoid changes in the database.
    

    To do it it's necessary:

    1- Install the EntityFramework into the Test Project. 2- Put the connection string into the app.config file of Test Project. 3- Reference the dll System.Transactions in Test Project.

    The unique side effect is that identity seed will increment when trying to insert, even when the transaction is aborted. But since the tests are made against a development database, this should be no problem.

    Sample code:

    [TestClass]
    public class NameValueTest
    {
        [TestMethod]
        public void Edit()
        {
            NameValueController controller = new NameValueController();
    
            using(var ts = new TransactionScope()) {
                Assert.IsNotNull(controller.Edit(new Models.NameValue()
                {
                    NameValueId = 1,
                    name1 = "1",
                    name2 = "2",
                    name3 = "3",
                    name4 = "4"
                }));
    
                //no complete, automatically abort
                //ts.Complete();
            }
        }
    
        [TestMethod]
        public void Create()
        {
            NameValueController controller = new NameValueController();
    
            using (var ts = new TransactionScope())
            {
                Assert.IsNotNull(controller.Create(new Models.NameValue()
                {
                    name1 = "1",
                    name2 = "2",
                    name3 = "3",
                    name4 = "4"
                }));
    
                //no complete, automatically abort
                //ts.Complete();
            }
        }
    }
    

提交回复
热议问题