我尝试使用xUnit测试Update方法,我不知道如何做到这一点,下面是我的代码:
Put method in controller:
[HttpPut]
[Route("{id}")]
public IActionResult Put([FromBody]BookDto book, [FromRoute]int id)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
var isUpdated = _service.Update(book);
if (!isUpdated)
{
return NotFound();
}
return Ok();
}
BookService更新方法:
public bool Update(BookDto book)
{
var bookDb = _context.Books.FirstOrDefault(x => x.Id == book.Id);
if(bookDb == null)
{
return false;
}
bookDb.Title = book.Title;
_context.SaveChanges();
var existingAuthors = _context.Book_Authors.Where(x => x.BookId == book.Id).ToList();
_context.Book_Authors.RemoveRange(existingAuthors);
_context.SaveChanges();
foreach (var AuthorsId in book.AuthorsId)
{
var newBookAuthors = new Book_Author()
{
BookId = book.Id,
AuthorId = AuthorsId
};
_context.Book_Authors.Add(newBookAuthors);
}
_context.SaveChanges();
return true;
}
BookDto:
public class BookDto
{
public int Id { get; set; }
public string Title { get; set; }
public List<int> AuthorsId { get; set; }
}
有什么建议如何写PutMethod测试使用Moq?
-
我建议收集测试用例:
给定- 我调用putThen它返回错误的请求 给定
- 我调用putThen它返回not Found 给定
- 当我调用putThen它返回ok
-
我建议每个测试用例使用AAA模式,例如:
- 安排设置一个图书服务模拟,当有人调用更新 时返回false
- :调用控制器的put方法
- 断言:验证返回的结果是否与预期的不一致
-
尝试整理。例如
public void GivenANonExistingBook_WhenICallPut_ThenItReturnsNotFound()
{
//Arrange
var book = ...;
var serviceMock = new Mock<IBookService>();
serviceMock.Setup(svc => svc.Update(It.IsAny<BookDto>()))
.Returns(false);
var sut = new YourController(serviceMock.Object);
//Act
var result = sut.Put(book, 0);
//Assert
var actionResult = result as NotFoundResult;
Assert.IsNotNull(actionResult);
}
验证服务的Update
方法只被调用过一次,使用book
变量:serviceMock.Verify(svc => svc.Update(book), Times.Once);
也是一个很好的做法。