lundi 4 avril 2016

Unit Testing a Controller - How Do I Handle the Connection String?

I can make it work, but I want to know what the best practice is and why. I have a Controller, a Model, and a Repository and now I want to Unit Test the Controller. I am just writing a simple test to ensure that the correct view is being returned.

This is my method in the controller:

    public ActionResult Selections(SelectionsViewModel model)
    {
        for (int i = 0; i < model.Sends.Count; i++)
        {
            Send send = new Send(new SendService(new Database().GetConnectionString()))
            {
                SendID = model.Sends[i].SendID,
                Title = model.Sends[i].Title,
                Subject = model.Sends[i].Subject,
                SentDate = model.Sends[i].SentDate,
                TimesViewed = model.Sends[i].TimesViewed,
                Include = model.Sends[i].Include,
                Exclude = model.Sends[i].Exclude
            };
            send.UpdateIncludeExclude();
        }

        return View(model);
    }

Here is my GetConnectionString() method in the Database class that is being sent via my SendService constructor.

    public string GetConnectionString()
    {
        return System.Configuration.ConfigurationManager.ConnectionStrings["DEVConnectionString"].ToString();
    }

And lastly, my unit test:

    [Test]
    public void TestAssignmentSelections()
    {
        var obj = new AssignmentController();

        var actResult = obj.Selections() as ViewResult;

        NUnit.Framework.Assert.That(actResult.ViewName, Is.EqualTo("Selections"));
    }

Now, my unit test fails, and I get why. My unit test project has no access to the web.config of the project I am testing where my connection string resides.

I've done some research, and apparently just adding a web.config to my unit test project and putting the connection string in there as well will make it work.. but that seems like a hack.

What's the best way to go about this? Is there another way to write my code to accommodate for this?

Aucun commentaire:

Enregistrer un commentaire