使用依赖注入和MOQ进行单元测试

时间:2016-01-05 16:09:39

标签: asp.net-mvc unit-testing mocking unity-container moq

我只是在学习依赖注入和模拟是如何工作的,但是我想要一些关于我如何设置几个测试的反馈。我可以让他们通过,但我不确定这是我需要的全部。

这是一个MVC应用程序,它使Web API调用返回数据。对于此示例,我在填充下拉列表的Web API中运行查询。

请告诉我关于我在这里做对或错的任何建议或我应采取的不同做法。

依赖注入的设置文件 - Unity.WebAPI(NuGet包)

UnityConfig.cs

public static class UnityConfig
{
    public static void RegisterComponents()
    {
        var container = new UnityContainer();

        // register all your components with the container here
        // it is NOT necessary to register your controllers

        // e.g. container.RegisterType<ITestService, TestService>();

        container.RegisterType<IDropDownDataRepository, DropDownDataRepository>();

        GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
    }
}

CONTROLLER

public class DropDownDataController : ApiController
{  
    private IDropDownDataRepository _dropDownDataRepository;

    //Dependency Injection (I'm using Unity.WebAPI)
    public DropDownDataController(IDropDownDataRepository dropDownDataRepository)
    {
        _dropDownDataRepository = dropDownDataRepository;
    }

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

REPOSITORY

public class DropDownDataRepository : IDropDownDataRepository
{
    //Is this fine in here, or should it be injected somehow too?
    private MyDatabaseEntities db = new MyDatabaseEntities();  

    public HttpResponseMessage DateList()
    {
        var sourceQuery = (from p in db.MyProcedure()
                           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;
    }
}

接口

public interface IDropDownDataRepository
{
    HttpResponseMessage DateList();
}  

UNIT TESTS

/// <summary>
/// Tests the DateList method is run
/// I pieced this kind of test together from examples online
/// I'm assuming this is good for a simple test
/// </summary>
[TestMethod]
public void DateListTest1()
{
    //Arrange
    var mockRepository = new Mock<IDropDownDataRepository>();
    mockRepository.Setup(x => x.DateList());           
    var controller = new DropDownDataController(mockRepository.Object);

    //Act
    controller.DateList();

    //Assert
    mockRepository.VerifyAll();
}



/// <summary>
/// Tests the DateList method returns correct status code.
/// This will run with success, but I'm not sure if that's just
/// because I'm telling it to return what I'm expecting.  
/// I welcome suggestions for improvement.
/// </summary>
[TestMethod]
public void DateListTest2()
{
    //Arrange
    var mockRepository = new Mock<IDropDownDataRepository>();
    mockRepository
        .Setup(x => x.DateList())
        //This will only succeed if I have the Returns property here,
        //but isn't that just bypassing the actual "test" of whether or
        //not this works?
        .Returns(new HttpResponseMessage(HttpStatusCode.OK));

    DropDownDataController controller = new DropDownDataController(mockRepository.Object);
    controller.Request = new HttpRequestMessage();
    controller.Configuration = new HttpConfiguration();

    //Act            
    var response = controller.DateList();

    //Assert
    Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
}

更新1

我的一个主要问题是.Returns属性实际上做了什么。在我的第二次单元测试中,我告诉它返回OK,然后检查它是否返回OK。我无法看到它是如何实际测试的。

1 个答案:

答案 0 :(得分:3)

  

这里的一个主要问题是.Returns属性实际上是什么   确实。在我的第二次单元测试中,我告诉它返回OK,然后检查   如果它返回OK。我看不出它是如何测试任何东西的。

代码:

mockRepository
        .Setup(x => x.DateList())
        //This will only succeed if I have the Returns property here,
        //but isn't that just bypassing the actual "test" of whether or
        //not this works?
        .Returns(new HttpResponseMessage(HttpStatusCode.OK));

mockRepository收到对DateList()的来电时,它会返回new HttpResponseMessage(HttpStatusCode.OK)

所以在里面

    [HttpGet]
    public HttpResponseMessage DateList()

单元测试到达行

return _dropDownDataRepository.DateList();

模拟对象触发并返回new HttpResponseMessage(HttpStatusCode.OK)

此测试的一个更好的名称将是DateListTest2,而不是DateList_Returns_Status_Code_From_Repository,因为这是您在测试中安排的内容。

说实话controller.DateList()没有太多的逻辑,所以这是你唯一的黄金路径测试。

相关问题