Im new to unittest and also confused i hope you help me understand couple of things, I would like to write a Xunit test for the following scenario:
I have a following controller:
[ApiController]
[Route("api/[controller]")]
public class HomeController : ControllerBase
{
public readonly IDataService _dataService;
public HomeController(IDataService dataservice)
{
_dataService = dataservice;
}
[HttpGet("/value")]
public IActionResult GetTotal(string name, string year)
{
var totalAmount = _dataService.GetToTalValue(name, year);
return Ok(totalAmount.Result);
}
i have repository class to talk to db i named it dataservice:
public interface IDataService
{
public Task<decimal> GetTotal(string name, string year)
}
the implemnation is simple i just write what im returning to make the long story shot:
public Task<decimal> GetTotal(string name, string year){
///here i connect to db and get data and return to controller
return Task.FromResult(totalAmount);
}
at the end,i have created a unit test by following some online tutorials:
public class UnitTest1
{
[Fact]
public void Test1()
{
var sut = new Mock<IDataService>();
sut.Setup(s => s.GetTotal("ASK", "1235")).ReturnsAsync(1231);
HomeController mm = new HomeController(sut.Object);
var result = mm.GetTotal("ASK", "1235");
///asset gives error because cant convert iactionresult to decimal
}
}
}
first i of all i don't get why do we need to write :
sut.Setup(s => s.GetTotal("ASK", "1235")).ReturnsAsync(1231);
because we are going to the exact thing with controller again:
HomeController mm = new HomeController(sut.Object);
var result = mm.GetTotal("ASK", "1235");
that setup means im passing two values to the GetTotal and expect 1231 right?whats the point of testing the controller then? Please help me understand it and my second question is the result i get from iactionresult is decimal but in assert i get error which i cant convert iactionresult to decimal
any help will be highly appreciated