Web API 控制器单元测试

Web API Controller Unit Testing

我有一个 N 层项目正在尝试测试 API 控制器,但流程有点复杂,这让我向你们征求一些意见...请提出任何建议非常感谢...

我收到一个错误

Object reference not Set to An Instance Of An Object

这是我的测试 class 和获得所有假症状的方法

[TestClass]
public class SymptomsControllerTest 
{

    private Mock<IAdministrationManagementService> _administrationManagementServiceMock;
    SymptomsController objController;
    IList<SymptomObject> listSymptoms;

    [TestInitialize]
    public void Initialize()
    {
        _administrationManagementServiceMock = new Mock<IAdministrationManagementService>();
        objController = new SymptomsController(_administrationManagementServiceMock.Object);

        listSymptoms = new List<SymptomObject>() {
         new SymptomObject() { Name = "Head1" },
         new SymptomObject() { Name = "Head2" },
         new SymptomObject() { Name = "Head3" }
        };
    }

    [TestMethod]
    public void Symptom_Get_All()
    {
        //Arrange
        _administrationManagementServiceMock.Setup(x => x.GetSymptoms()).ReturnsAsync(listSymptoms);

        //Act
        var result = objController.Get() as List<SymptomObject>;

        //Assert
        Assert.AreEqual(result.Count, 3);
        Assert.AreEqual("Head1", result[0].Name);
        Assert.AreEqual("Head2", result[1].Name);
        Assert.AreEqual("Head3", result[2].Name);

    }

}

正在尝试与之通信的服务看起来像这样

 public Task<IList<SymptomObject>> GetSymptoms()
    {
        return Task.Run(() =>
        {
            try
            {
                using (var _uow = new HomasUoW())
                {
                    var entities = _uow.Symptoms.GetAll().Where(x => x.isDelete == false);

                    if (entities.Count() > 0)
                    {
                        IList<SymptomObject> list = new List<SymptomObject>();
                        foreach (var entity in entities)
                        {
                            var obj = AutoMapper.Mapper.DynamicMap<Symptom, SymptomObject>(entity);

                            obj.Name = entity.Name;

                            list.Add(obj);


                        }

                        return list;
                    }
                    else
                    {
                        throw new InvalidOperationException(Resources.NonExistingObjectRetrievalError);
                    }
                }

            }
            catch (Exception)
            {

                throw;
            }
        });

    }

并且 API 控制器看起来像这样

 public IHttpActionResult Get()
    {
        try
        {
            var symptoms = _Service.GetSymptoms();

            if (symptoms != null)
            {
                return Ok(symptoms);
            }

            return NotFound();
        }
        catch (Exception ex)
        {

            return InternalServerError(ex);
        }
    }

请仔细查看是否遗漏了任何不允许测试通过的内容。

根据您的评论:

the null exception is coming from this line of code Assert.AreEqual(result.Count, 3);

显然 result 对象是 null。看看你是如何得到那个对象的:

var result = objController.Get() as List<SymptomObject>;

即使 Get() return 是什么,as 关键字的行为也是如此,当您尝试解释一个对象 as 错误的类型时,结果将是 null。您试图将该对象解释为 List<SymptomObject>。但是 Get() return 是什么?

public IHttpActionResult Get()

您不能将 IHttpActionResult 转换为 List<SymptomObject>。您有两个选择:

  1. 您的 WebAPI 控制器应该 return a List<SymptomObject>(我认为这可能是更好的方法,但是在所示代码的范围之外还有更多的考虑因素),或者;
  2. 您的测试应该验证 IHttpActionResult 正在 returned。