单元测试怎么写?包含什么东西?
说下我自己的心得。
按照官方文档创建对应的单元测试项目,然后分析接口会出现哪几种结果或者错误,然后给出相应的输入参数。
单元测试方法有通用的3A模型(Arrange,Action,Assert)。
下面是我自己写的其中一个接口的单元测试,如果有问题大家一起讨论。
我要测试的接口方法:
[HttpPost]
[Route("api/Account/GetEpVIPInfo")]
public object GetEpVIPInfo(GetEpVIPInfoRequest request)
{
var result = new BaseViewModel
{
Info = CommonData.FailStr,
Message = CommonData.FailStr,
Msg = false,
ResultCode = CommonData.FailCode
};
var viewModel = new GetEpVIPInfoViewModel();
var vipModel = AccountService.GetEpVIPInfo(request);
if (vipModel != null)
{
viewModel.VIPInfoId = GetEPVIPInfo(vipModel.Name);
}
else
{
viewModel.VIPInfoId = 0;
}
result = new BaseViewModel
{
Info = viewModel,
Message = CommonData.SuccessStr,
Msg = true,
ResultCode = CommonData.SuccessCode
};
return result;
}
单元测试方法:
#region GetEpVIPInfo
/// <summary>
/// 错误的参数,不合法参数
/// </summary>
[TestMethod]
public void GetEpVIPInfo_WithErrorParams_ExceptTrueResponse()
{
//Arrange
var accountController = new AccountController();
var db = new Mock<IAccountService>();
db.Setup(d => d.GetEpVIPInfo(It.IsAny<GetEpVIPInfoRequest>()))
.Returns((T_VIPInfo)null);
accountController.AccountService = db.Object;
//Action
var request = new GetEpVIPInfoRequest { CityId = "3202", EPId = -1 };
var result = accountController.GetEpVIPInfo(request);
var obj = result.GetBaseViewModel();
//Assert
Assert.IsTrue(obj.Msg);
Assert.AreEqual(CommonData.SuccessStr, obj.Message);
Assert.AreEqual(CommonData.SuccessCode, obj.ResultCode);
}
/// <summary>
/// 正确参数返回值
/// </summary>
[TestMethod]
public void GetEpVIPInfo_WithRightParams_ExceptTrueResponse()
{
//Arrange
var accountController = new AccountController();
var db = new Mock<IAccountService>();
db.Setup(d => d.GetEpVIPInfo(It.IsAny<GetEpVIPInfoRequest>()))
.Returns(new T_VIPInfo { Name = "月度会员", Id = 4 });
accountController.AccountService = db.Object;
//Action
var request = new GetEpVIPInfoRequest { CityId = "3202", EPId = 1 };
var result = accountController.GetEpVIPInfo(request);
var obj = result.GetBaseViewModel();
var viewModel = new GetEpVIPInfoViewModel { VIPInfoId = 4 };
//Assert
Assert.IsTrue(obj.Msg);
Assert.AreEqual(CommonData.SuccessStr, obj.Message);
Assert.AreEqual(CommonData.SuccessCode, obj.ResultCode);
Assert.AreEqual(viewModel.ToJsonStr(), obj.Info.ToJsonStr());
}
#endregion
大家注意到了,我的单元测试方法利用region隔开了,这样方便大家编码,通过region区分接口模块,查找时也比较方便,养成良好的习惯更好。
我这个接口只有两种情况,所以只写了两种测试方法,如果接口再有其他的可能的情况时,可以再增加单元测试方法。
关于空参数:我们的接口项目有拦截器,会在拦截器里面判断该接口是否需要参数,如果需要传递参数而请求该接口的请求中不包含参数值或者参数为空时则阻断该请求,不会到接口。