'NTest with parameterize controller using Asp.net Core
I am working on application where I need to unit test my application but it gives me an error of No suitable constructor was found and that is because I have injected service in my controller. here is my code.
public class UrlsController : Controller
{
private readonly ILogger<UrlsController> _logger;
private readonly IBrowserDetector browserDetector;
private readonly HelperService helperService;
private readonly IHttpContextAccessor httpContextAccessor;
private readonly UrlService urlService;
private readonly UrlStateService urlStateService;
private string localurl;
public UrlsController(
ILogger<UrlsController> logger,
IBrowserDetector browserDetector,
HelperService helperService,
UrlService urlService,
UrlStateService urlStateService,
IHttpContextAccessor httpContextAccessor
)
{
this.browserDetector = browserDetector;
this.helperService = helperService;
this.httpContextAccessor = httpContextAccessor;
this.urlService = urlService;
this.urlStateService = urlStateService;
this.localurl = this.httpContextAccessor.HttpContext.Request.Scheme
+ "://" + this.httpContextAccessor.HttpContext.Request.Host;
this._logger = logger;
}
public async Task<IActionResult> Index(bool error = false)
{
var model = new HomeViewModel();
model.Error = error;
model.LocalUrl = localurl;
model.UrlList = await urlService.GetUrlList();
return View(model);
}
}
I am calling index method from UnitTest application and my implementation of unit test is as follow. and I also want to insert data so how can I manage to test my both method i-e Index and Create.
public class UrlsControllerTest
{
private readonly ILogger<UrlsController> _logger;
private readonly IBrowserDetector browserDetector;
private readonly HelperService helperService;
private readonly IHttpContextAccessor httpContextAccessor;
private readonly UrlService urlService;
private readonly UrlStateService urlStateService;
public UrlsControllerTest(
ILogger<UrlsController> logger,
IBrowserDetector browserDetector,
HelperService helperService,
UrlService urlService,
UrlStateService urlStateService,
IHttpContextAccessor httpContextAccessor
)
{
}
[SetUp]
public async Task Setup()
{
var model = new HomeViewModel();
model.Urlmodel.OrignalUrl = "https://stackoverflow.com/";
UrlsController urlController =
new UrlsController(
this._logger, this.browserDetector,
this.helperService, this.urlService,
this.urlStateService, this.httpContextAccessor);
await urlController.Create(model);
}
[Test]
public async Task TestIndex()
{
UrlsController urlController =
new UrlsController(this._logger, this.browserDetector,
this.helperService, this.urlService, this.urlStateService,
this.httpContextAccessor);
var _result = await urlController.Index();
Assert.IsNotNull(_result);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
