Answer the question
In order to leave comments, you need to log in
How to write Unit Test for ASP.NET MVC?
There is a testable method:
public class CategoryModelService : ICategoryModelService
{
private readonly ICategoryModelRepository _categoryModelRepository;
private readonly ICoastModelRepository _coastModelRepository;
public CategoryModelService(ICategoryModelRepository _categoryModelRepository, ICoastModelRepository
_coastModelRepository)
{
this._categoryModelRepository = _categoryModelRepository;
this._coastModelRepository = _coastModelRepository;
}
public async Task<CategoryModel> AddCategory(CategoryModel category)
{
var result = await _categoryModelRepository.AddCategory(category);
if (result != null)
{
return category;
}
else
{
return null;
}
}
}
[TestClass]
public class CategoryModelServiceTest
{
[TestMethod]
public void MyTest()
{
Mock<ICategoryModelRepository> _categoryModelRepository = new Mock<ICategoryModelRepository>();
Mock<ICoastModelRepository> _coastModelRepository = new Mock<ICoastModelRepository>();
CategoryModelService categoryModelService = new CategoryModelService(_categoryModelRepository.Object, _coastModelRepository.Object);
CategoryModel model = new CategoryModel()
{
AutorCategoryId = ObjectId.GenerateNewId().ToString(),
Id = ObjectId.GenerateNewId().ToString(),
Income = false,
Name = "Name",
NetIncome = true
};
CategoryModel result = new CategoryModel();
Task.Run(async () => { result = await categoryModelService.AddCategory(model); }).Wait();
Assert.IsNotNull(result);
}
}
Answer the question
In order to leave comments, you need to log in
Mocks need to be configured. They return the default value of the required type by default. Thus, inside AddCategory
the mock repository, it always gives result == null
and, accordingly, null
returns, the test falls.
var model = new CategoryModel { ... };
var categoryModelRepository = new Mock<ICategoryModelRepository>();
categoryModelRepository.Setup(x => x.AddCategory(model))
.Returns(model);
// Или
categoryModelRepository.Setup(x => x.AddCategory( It.IsAny<CategoryModel>() ))
.Returns(model);
// Act...
Assert.IsNotNull(result);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question