How to refactor and unit test this method.
[HttpPost]
[Consumes(MediaTypeNames.Application.Json)] [ProducesResponseType(StatusCodes.Status201Created)] [ProducesResponseType(StatusCodes.Status400BadRequest)]
public IActionResult Post([FromBody] BlogRequest blogModel)
{
try
{
if (ModelState.IsValid)
{
var userId = User.Claims.Where(x => x.Type == "uid").FirstOrDefault()?.Value;
if(userId == null) return BadRequest(ModelState);
var blog = _mapper.Map<Blog>(blogModel);
blog.UserId = userId;
_unitOfWork.BlogRepository.Add(blog);
_unitOfWork.save();
return Created("~api/blogs", blogModel);
}
}
catch (Exception ex)
{
ModelState.AddModelError("AddBlog", ex.Message);
}
return BadRequest(ModelState);
}
[HttpPost]
[Consumes(MediaTypeNames.Application.Json)] [ProducesResponseType(StatusCodes.Status201Created)] [ProducesResponseType(StatusCodes.Status400BadRequest)]
public IActionResult Post([FromBody] BlogRequest blogModel)
{
try
{
if (ModelState.IsValid)
{
var userId = User.Claims.Where(x => x.Type == "uid").FirstOrDefault()?.Value;
if(userId == null) return BadRequest(ModelState);
var blog = _mapper.Map<Blog>(blogModel);
blog.UserId = userId;
_unitOfWork.BlogRepository.Add(blog);
_unitOfWork.save();
return Created("~api/blogs", blogModel);
}
}
catch (Exception ex)
{
ModelState.AddModelError("AddBlog", ex.Message);
}
return BadRequest(ModelState);
}
mapper
& _unitOfWork
but how should i mock authorized user's id ?1 Reply
I'm not really sure what you're testing here, or at least, what the value is.