I have been following this tutorial and trying to understand this Xunit test for an update service.
The service is as follows:
public async Task<Category> Update(Category category)
{
if (_categoryRepository.Search(c => c.Name == category.Name && c.Id != category.Id).Result.Any())
return null;
await _categoryRepository.Update(category);
return category;
}
And the Xunit test:
[Fact]
public async void Update_ShouldNotUpdateCategory_WhenCategoryDoesNotExist()
{
var category = new Category()
{
Id = 1,
Name = "Test Category 1"
};
var categoryList = new List<Category>()
{
new Category()
{
Id = 2,
Name = "Test Category 2"
}
};
_categoryRepositoryMock.Setup(c => c.Search(c => c.Name == category.Name && c.Id != category.Id))
.ReturnsAsync(categoryList);
var result = await _categoryService.Update(category);
Assert.Null(result);
}
I know that from this authors notes about what the test is supposed to do is contradicting what the method name's when-condition (It's about 3/4 the way the linked tutorial page):
- The method does not update a category when the updated category name already exists.
The test is returning null, but I'm not sure if it's doing it for the right reason.
Is it that it can't find the category in the mock repo? As I tried adding a category in hopes that it would find the category and fail the test, but it still came back as null:
new Category()
{
Id = 1,
Name = "Test Category One"
}
Or is it that the mocking of the validation which returns categoryListing and even though it is not the correct record (as it's name is not a match) enough to cause the null? (I'm guessing it is this one)
I am new to unit testing, but it doesn't feel like a good test shouldn't the mock repository be preloaded with records and then the updated record have it's validation tested against it? I'm guessing this would just be another way of doing this, however, how would I change the code to accomplish that?