ASP.NET MVC > Unit testing

Test controller method that access data from database in ASP.NET MVC

How to test a controller method that is accessing data from database?


In order to test a Unit test method that access the action method of the controller that uses database, we need to make some changes in the app.config and other files into the Test project as well as Web application we are going to test.

Add following .dlls reference to the Test project.

  1. EntityFramework.dll
  2. EntityFramework.SqlServer.dll
  3. System.Web.Mvc.dll
  4. WebGrease.dll

We need few more .dlls in the reference, below are highlighted .dlls into the Unit test project.

Make below necessary changes to the App.config file of the Unit test project.

APP.CONFIG FILE

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit
http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework"
type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection,
EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
requirePermission="false" />
  </configSections>

<connectionStrings>
  <add name="DefaultConnection" connectionString="Data Source=SNITFunda;Initial
Catalog=TrainingDatabase;Integrated Security=True;Integrated
Security=SSPI;MultipleActiveResultSets=true" providerName="System.Data.SqlClient"/>
  </connectionStrings>

<entityFramework>
  <defaultConnectionFactory
type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
  <providers>
   <provider invariantName="System.Data.SqlClient"
type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"
/>
    </providers>
  </entityFramework>

</configuration>

Notice the changes in the above file that is highlighted. Change the database connection string, it should be same as the Web application (to test) web.config connection string.

In the Web Application project go to ~/Models/IdentityModels.cs and look for following DbConnext code block

~/MODELS/IDENTITYMODELS.CS CODE

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>

{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
        // This is mandatory to run the db related test

         Database.SetInitializer<WebApplication1.Models.ApplicationDbContext>(null);
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

}

Look at the highlighted code statement. This is mandatory to write otherwise we get following errors when we run the unit test.

Test method WebApplicationTest.UnitTest1.CheckFirstName threw exception:

System.InvalidOperationException: The model backing the 'ApplicationDbContext' context has changed since the database was created. Consider using Code First Migrations to update the database

(http://go.microsoft.com/fwlink/?LinkId=238269).

Now, let’s write the Unit test method.

UNIT TEST METHOD

       [TestMethod]
        public void CheckFirstName()
        {
            // Arrange
            var controller = new PersonalDetailsController();
            
            // Act
            var result = controller.Details(1) as ViewResult;
            WebApplication1.Models.PersonalDetail person =
(WebApplication1.Models.PersonalDetail) result.Model;

            // Assert
            Assert.AreEqual("Sheo", person.FirstName);
        }

Running the above unit test gives success result as the record from the PersonalDetails table having AutoId 1 having first name as “Sheo”.

If we change the first parameter value (I have changed to “Sheo0”) of Assert.AreEqual method (the expected parameter), and run the test it gives following error.

 Views: 11651 | Post Order: 137



Write for us






Hosting Recommendations