Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No connectionString could be found in the test project application config file

I had a solution with web project and I decided to add a Unit Test project to the solution. While running tests one of them fail with this error:

Result Message: 
Test method DetailsRoleController threw exception: 
System.InvalidOperationException: No connection string named 'EquipmentEntities' could be found in the application config file.

Here my test script:

  [TestClass]
public class RoleControllerTest
{
    RoleController RC = new RoleController();
    [TestMethod]
    public void IndexRoleController()
    {
    }
    [TestMethod]
    public void DetailsRoleController()
    {
        var result = RC.Delete(1);
        Assert.IsNotNull(result);
    }
}

and the controller method:

public ActionResult Details(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Role role = db.Roles.Find(id);
        if (role == null)
        {
            return HttpNotFound();
        }
        return View(role);
    }

Why does this test fails?

Isn't this test case runing using connectrionstrings/context from main project?

Ok I edited my appconfig and its looking now this:

<configuration>
  <appSettings>

  </appSettings>
  <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>
  <connectionStrings>
    <add name="EquipmentEntities" connectionString="metadata=res://*/Models.MagazynModel.csdl|res://*/Models.MagazynModel.ssdl|res://*/Models.MagazynModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=XYZ\sqlexpress;initial catalog=Equipment;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
</configuration>

but now I have another error:

Result Message: Unable to create instance of class magazynTest.Controllers.RoleControllerTest. Error: System.TypeInitializationException:
 The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception. ---> System.Configuration.ConfigurationErrorsException:
 Configuration system failed to initialize ---> System.Configuration.ConfigurationErrorsException: Unrecognized configuration section entityFramework. 
like image 294
szpic Avatar asked Feb 14 '14 11:02

szpic


People also ask

How do you read connectionString from configuration file into code behind?

To read the connection string into your code, use the ConfigurationManager class. string connStr = ConfigurationManager. ConnectionStrings["myConnectionString"].

Where are connectionStrings in web config?

Connection strings go inside a <connectionStrings> element. The traditional place to put <connectionStrings> seems to be immediately before <appSettings> but its precise location shouldn't matter.


2 Answers

It is not the case that it will pick it up from your Web application by default.

It will be looking for it in the current project where it is running.

You will have to add it into an app.config file in the Unit Test project containing your connection settings.

Another approach is to inject it into your controller, this way in your tests you can pass in a mock object which would prevent ever having to deal with an actual db instance at all.

If you re-designed the approach to use a repository pattern, without seeing your classes something like below:

public class RoleController : Controller
   {
      private IRoleRepository roleRepository;

      // This constructor would not be needed if you were to use IOC container
      public RoleController ()
      {
         this.roleRepository = new RoleRepository(new RoleContext());
      }

      public RoleController(IRoleRepository studentRepository)
      {
         this.roleRepository = roleRepository;
      }
      ....

You could then mock out the repository like below:

[TestClass]
public class RoleControllerTest
{
    private Mock<IRoleRepository> _roleRepository;

    [SetUp]
    public void SetUp()
    {
    _roleRepository = new Mock<IRoleRepository>();

    }



    [TestMethod]
    public void IndexRoleController()
    {
    }
    [TestMethod]
    public void DetailsRoleController()
    {
        RoleController RC = new RoleController(_roleRepository.Object);
        var result = RC.Delete(1);
        Assert.IsNotNull(result);
    }
}

See here for more info:

http://kakimotonline.com/2011/02/13/tdd-in-asp-net-mvc-applications-with-moq-framework/

like image 158
hutchonoid Avatar answered Nov 16 '22 00:11

hutchonoid


copy the ConnectionStrings section from your webConfig to the test projects appConfig

like image 38
Parv Sharma Avatar answered Nov 16 '22 00:11

Parv Sharma