i'm new to unit test in c#, i want to test for the 3 possible outcome, when modalstate is invalid, adding new category and internal server error. here is the method i want to test.
[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");
}
}
and here is my code so far, please does anyone know how i can access the 3 possible responses?
[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();
}
It is not unit testing. If you test Controller it's about integration testing. Ok. If you want 3 test case, you should write 3 test. Because one test is one test case. Don't try test it in one place
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.