我目前正在研究ASP.NET核心控制器的单元测试,我偶然发现了一个有趣的场景.在我的项目中,UpdateUser
模型中的StatusId
属性声明为int
,但其对应的数据库类型为tinyint
.在某些条件下,API接受值为StatusId
的-1
.
下面是相关代码的一个片段:
public static class Constant
{
public static readonly int[] AdminRoleId = new int[] { 1, 2 };
}
public class UpdateUserBase
{
public int Id { get; set; }
}
public class UpdateUser : UpdateUserBase
{
public string Name { get; set; }
public int StatusId { get; set; }
}
// ... Controller code ...
public async Task<IActionResult> UpdateUser(UpdateUser user)
{
if (!Constant.Constant.AdminRoleId.Contains(UserRoleId))
user.StatusId = 0; // If it's 0, the status won't be changed
int result = await _service.UpdateUser(user);.
return result switch
{
> 0 => Ok(),
_ => BadRequest("Update Failed.")
};
}
我特别感兴趣的是,当StatusId
设置为-1
时,我应该如何处理单元测试.考虑到数据类型(C#int
和数据库tinyint
)的不同,有什么我应该记住的注意事项或最佳实践吗?我是否应该专门测试StatusId
等于-1
的场景?
您的指导和见解将对我在测试过程中提供极大的帮助.谢谢!