I’m new at asp.net and moq and xunit test, I want to create a test case for my asp.net project. I have the service file that is CRUD action,
I have been written for Create Method it’s Ok but at Get, GetAll, Delete, Put method I don’t know what should I setup
public void Test1()
{
var tutorRequest = new Mock<ITutorRequestService>();
//What should i set up for Get and GetAll
tutorRequest.Setup(r => r.Get(It.IsAny<int>(), It.IsAny<string?>()))
.ReturnsAsync(() => new Entity());
var logger = new Mock<ILogger<TutorRequestsController>>();
var controller = new TutorRequestsController(tutorRequest.Object, logger.Object);
var rs = controller.Get(1, "");
Assert.NotNull(rs);
}
My service class
public async Task<TutorRequest> Create(TutorRequestModel tutor)
{
var entity = _mapper.Map<TutorRequest>(tutor);
CheckDataNotNull("entity", entity);
entity = await _repository.Add(entity);
return _mapper.Map<TutorRequest>(entity);
}
public async Task<TutorRequest> Delete(int tutorId)
{
var entity = await _repository.Delete(tutorId);
return _mapper.Map<TutorRequest>(entity);
}
public async Task<Entity> Get(int id, string? fields)
{
var entity = await _repository.Get(id);
CheckDataNotNull("tutor request", entity);
var shaped = _dataShaper.ShapeData(entity, fields);
CheckDataNotNull("shaped", shaped);
return _mapper.Map<Entity>(shaped);
}
public PageList<Entity> GetAll(TutorRequestParams param)
{
var listAll = _repository.GetAll();
CheckDataNotNull("shaped", listAll);
Search(ref listAll, param);
var sortedStudent = _sortHelper.ApplySort(listAll, param.OrderBy);
var shapedOwners = _dataShaper.ShapeData(sortedStudent, param.Fields);
return PageList<Entity>.ToPageList(shapedOwners, param.PageNume, param.PageSize);
}
public async Task<TutorRequest> Update(TutorRequestModel tutor)
{
var entity = _mapper.Map<TutorRequest>(tutor);
entity = await _repository.Update(entity);
return _mapper.Map<TutorRequest>(entity);
}
2
Answers
If you’re expecting the
GetAll
method to return something, you need to set up the call for the mocked service.I have write a test case for Get method that similar to your example, you can check it out