单元测试方法无法识别app conf连接字符串

时间:2016-10-28 00:41:34

标签: c# asp.net asp.net-mvc unit-testing

我一直致力于ASP.NET MVC项目Visual Studio 2012 Ultimate with Entity Framework。我必须在我的解决方案中包含一个单元测试项目。我的问题在于测试方法(称为Index())无法识别app.config中的应用程序连接字符串。我的单元测试方法是:

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using ELSORegistry;
using ELSORegistry.DataAccess;
using ELSORegistry.Controllers;



namespace ELSORegistryUnitTests
{
    [TestClass]
    public class FirstControllerTest
    {
        [TestMethod]
        public void Index()
        {
            //Arange
            HomeController controller = new HomeController();

            //Act
            Guid? myGuid = new Guid("941b1615-f21b-4e2c-8fa8-0ed0d3f2de53");
            ViewResult result = controller.Index(myGuid) as ViewResult;

            //Assert
            Assert.IsNotNull(result);
        }
    }
}

Home Controller中的我的Index()动作是:

using System;
using System.Diagnostics.Contracts;
using System.Web.Mvc;
using ELSORegistry.DataAccess;
using ELSORegistry.Models;
using Kendo.Mvc.UI;
using WebGrease.Css.Extensions;
using ELSORegistry.Extensions;



using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Validation;
using System.Linq;
using Kendo.Mvc.Extensions;
using System.Diagnostics;
using ELSORegistry.Helpers;
using Newtonsoft.Json;


namespace ELSORegistry.Controllers
{
    [Authorize]
    public class HomeController : Controller
    {
        [Authorize(Roles = "ECLS Center Data Manager, ECLS Center Administrator,ECLS Center Data Viewer, ECLS Center Data Entry")]
        //[RequireHttps]  // Enable for production
        public ActionResult Index(Guid? CenterId)
        {
            //----------------------------------------
            // Remove references to previous patients
            //----------------------------------------    
            Session.Remove("Patient");
            Session.Remove("PatientSummary");
            Session.Remove("Run");
            Session.Remove("RunDetail");
            Session.Remove("Addendum");

            // if user have this session then he will get edit forms. // Yes if Add new
            Session.Remove("AddNewMode");
            Session.Remove("AddNewRunId");
            Center center;
            if (CenterId == null)
            {
                center = Session["Center"] as Center;
                Contract.Assert(center != null);
            }
            else
            { // set center by selected centerId from dropdownlist
                center = new Repository().GetCenter(new Guid(CenterId.ToString()));
                Session["Center"] = center;
                center = Session["Center"] as Center;
                Contract.Assert(center != null);
            }


            ViewBag.RunCounts = Session["RunCounts"];
            ViewBag.ChartSummaries = Session["ChartSummaries"];



            return View(new QuickAdd());

        }

错误在于:

center = new Repository().GetCenter(new Guid(CenterId.ToString()));

控制器。 GetCenter的方法是:

public Center GetCenter(Guid centerId)
        {
            try
            {
                using (var context = new ELSORegistryEntities())
                {
                    var center = context.Centers.FirstOrDefault(c => c.CenterId == centerId);
                    return center;
                }
            }
            catch (InvalidOperationException ex)
            {
                throw new DataException(string.Format("Error retrieving center for CenterId {0}", centerId), ex);
            }
        }

和app.config位于ELSORegistry.DataAccess项目中,该项目包含在测试中。 ELSORegistryEntities()类是:

namespace ELSORegistry.DataAccess
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    using System.Data.Entity.Core.Objects;
    using System.Linq;

    public partial class ELSORegistryEntities : DbContext
    {
        public ELSORegistryEntities()
            : base("name=ELSORegistryEntities")
        {            
        }

连接字符串是:

<connectionStrings>
        <add name="ELSORegistryEntities" connectionString="metadata=res://*/DataModel.csdl|res://*/DataModel.ssdl|res://*/DataModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=NELAPC\NELA2014;initial catalog=ELSORegistry2;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework&quot;" providerName="System.Data.EntityClient" />
    </connectionStrings>

错误是:“测试方法ELSORegistryUnitTests.FirstControllerTest.Index抛出异常:System.Data.DataException:检索CenterId的中心时出错941b1615-f21b-4e2c-8fa8-0ed0d3f2de53-&gt; System.InvalidOperationException :在应用程序配置文件中找不到名为'ELSORegistryEntities'的连接字符串“。 我该如何解决这个问题?提前感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

您需要在单元测试项目中包含app.config文件。仅尊重/使用正在运行的项目(在本例中为单元测试项目)app.config。