mardi 29 décembre 2015

Unit Testing A Web API That Uses Windows Authentication

Here's my situation. I have a Web API in an intranet site that populates a dropdown. The query behind the dropdown takes the windows username as a parameter to return the list.

I realize I don't have all of this set up correctly because I'm not able to unit test it. I need to know how this "should" be set up to allow unit testing and then what the unit tests should look like.

Additional Info - This is an ASP.NET MVC 5 application.

INTERFACE

public interface ITestRepository
{
    HttpResponseMessage DropDownList();
}

REPOSITORY

public class TestRepository : ITestRepository
{
    //Accessing the data through Entity Framework
    private MyDatabaseEntities db = new MyDatabaseEntities();

    public HttpResponseMessage DropDownList()
    {
        //Get the current windows user
        string windowsUser =  HttpContext.Current.User.Identity.Name;

        //Pass the parameter to a procedure running a select query
        var sourceQuery = (from p in db.spDropDownList(windowsUser)
                           select p).ToList();

        string result = JsonConvert.SerializeObject(sourceQuery);
        var response = new HttpResponseMessage();
        response.Content = new StringContent(result, System.Text.Encoding.Unicode, "application/json");

        return response;            
    }
}

CONTROLLER

public class TestController : ApiController
{
    private ITestRepository _testRepository;

    public TestController()
    {
        _testRepository = new TestRepository();
    }

    [HttpGet]
    public HttpResponseMessage DropDownList()
    {
        try
        {
            return _testRepository.DropDownList();
        }
        catch
        {
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire