我的操作的第一行通过额外的集成测试进行了测试。第二行是用额外的单元测试测试自动映射器映射的东西第三行然后是未经测试的。
下面的单元测试是否测试第三行?因为它只是测试返回类型。
这对我来说似乎很愚蠢或太琐碎。该方法还应该返回什么???
此操作中没有 if/else 逻辑。因此,仅测试 type == JsonNetResult 对我来说似乎是多余的。如果有人删除了 success = true 匿名类型,我什至不会在我的单元测试中意识到。
我应该用 QUnit 测试 JsonNetResult 的数据吗?
我会很高兴得到一些指导和提示,因为返回 Json 数据的操作让我发疯......它只是从 db 中获取数据并将其放入 JsonNetResult 对象中。
行动
[HttpGet]
public ActionResult GetTemplateRootUnits(int templateId)
{
IEnumerable<Unit> units = _dataProvider.GetTemplateRootUnits(templateId);
IEnumerable<UnitTreeViewModel> unitTreeViewModels = Mapper.Map<IEnumerable<Unit>, IEnumerable<UnitTreeViewModel>>(units);
return new JsonNetResult(new { data = unitTreeViewModels, success = true });
}
单元测试
[Test]
public void GetTemplateRootUnits_TemplateExists_ReturnsJsonNetResult()
{
// ARRANGE
Mock<IUnitDataProvider> mock1 = new Mock<IUnitDataProvider>();
Mock<IMappingEngine> mock2 = new Mock<IMappingEngine>();
Mock<ControllerContext> mock3 = new Mock<ControllerContext>();
UnitController controller = new UnitController(mock1.Object, mock2.Object);
mock1.Setup(m => m.GetTemplateRootUnits(1)).Returns(new List<Unit>
{
new Unit{ UnitId = 1, Name = "Name1", HasChildren = false},
new Unit{ UnitId = 2, Name = "Name2", HasChildren = false},
new Unit{ UnitId = 3, Name = "Name3", HasChildren = false},
});
var unitTreeViewModels = new List<UnitTreeViewModel>
{
new UnitTreeViewModel { Id = 1, Name = "Name1", HasChildren = false},
new UnitTreeViewModel { Id = 2, Name = "Name2", HasChildren = false},
new UnitTreeViewModel { Id = 3, Name = "Name3", HasChildren = false},
};
// Thats the way AutoMapper is mocked
mock2.Setup(m => m.Map<IEnumerable<Unit>, IEnumerable<UnitTreeViewModel>>(It.IsAny<IEnumerable<Unit>>())).Returns(unitTreeViewModels);
// ACT
ActionResult result = controller.GetTemplateRootUnits(1);
// ASSERT - check that the dataProvider.GetTestplanRootUnits() was called
mock1.Verify(m => m.GetTemplateRootUnits(1));
// ASSERT
Assert.IsInstanceOfType(typeof(JsonNetResult), result);
}
JsonNetResult.cs
public class JsonNetResult : ContentResult
{
private readonly object _data;
public JsonNetResult(object data)
{
_data = data;
}
public override void ExecuteResult(ControllerContext context)
{
Content = JsonConvert.SerializeObject(_data);
ContentType = "application/json";
base.ExecuteResult(context);
}
public object Data { get { return _data; } }
}