[英]how to test for the responses of a method using NUnit test
我是 C# 单元测试的新手,我想测试 3 种可能的结果,当 modalstate 无效时,添加新类别和内部服务器错误。 这是我要测试的方法。
[HttpPost]
public async Task<ActionResult<Category>> CreateCategory(CreateCategoryDTO createCategoryDto)
{
if (!ModelState.IsValid)
{
_logger.LogError($"Invalid POST attempt in {nameof(CreateCategory)}");
return BadRequest(new Response{ Status = "fail", Message = "Invalid inputs"});
}
try
{
var category = _mapper.Map<Category>(createCategoryDto);
await _unitOfWork.Categories.Add(category);
await _unitOfWork.Save();
return CreatedAtRoute("GetCategory", new {id = category.Id}, category);
}
catch (Exception e)
{
_logger.LogError($"Something went wrong in the {nameof(CreateCategory)}");
return StatusCode(500, "Internal server error. Please try again later");
}
}
到目前为止,这是我的代码,请问有人知道我如何访问这 3 个可能的响应吗?
[SetUp]
public void Setup()
{
_categories = new Mock<IRepository<Category>>();
_unitOfWork = new Mock<IUnitOfWork>();
_unitOfWork.SetupGet(work => work.Categories).Returns(_categories.Object);
_logger = new Mock<ILogger<CategoryController>>();
_mapper = new Mock<IMapper>();
_categoryController = new CategoryController(_logger.Object, _mapper.Object,_unitOfWork.Object);
}
[Test]
public void CreateCategoryTest()
{
_categoryController.ModelState.AddModelError("test", "test");
var result = _categoryController.CreateCategory(new CreateCategoryDTO()).GetAwaiter().GetResult();
}
这不是单元测试。 如果您测试控制器,则它是关于集成测试。 好的。 如果你想要 3 个测试用例,你应该写 3 个测试。 因为一个测试就是一个测试用例。 不要尝试在一个地方进行测试
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.