Reputation: 7866
I just started with unit testing using Nunit with my WebApi project.
I've developed one test case for my controller:
private readonly INewsBusinessLogic _newsBusinessLogic;
[Test]
public async Task GetAllNews()
{
// Arrange
var controller = new NewsController(_newsBusinessLogic);
controller.Configuration = new System.Web.Http.HttpConfiguration();
controller.Request = new System.Net.Http.HttpRequestMessage();
// Act
var actionResult = await controller.Get();
//assert
Assert.IsNotNull(actionResult);
}
Api controller:
public class NewsController : ApiController
{
private readonly INewsBusinessLogic _newsBusinessLogic;
public NewsController(INewsBusinessLogic newsBusinessLogic)
{
_newsBusinessLogic = newsBusinessLogic;
}
public async Task<IHttpActionResult> Get()
{
return Ok(await _newsBusinessLogic.GetNewsUpdates());
}
}
When I debug my test it gives me an error of NullReferenceException
on Act , well I know very well that What is a NullReferenceException?. But cannot figure it out, why this is occurred and how to solve it.
Side Note: I'm not using any ORM.
Upvotes: 1
Views: 120
Reputation: 246998
well for one, you are passing in a null
variable into NewsController
constructor as you have not shown in your example where a value is assigned to _newsBusinessLogic
Here is an example using Moq of how to mock the controller's dependency
[Test]
public async Task GetAllNews()
{
// Arrange
var newsBusinessLogicMock = new Mock<INewsBusinessLogic>();
newsBusinessLogicMock
.Setup(m => m.GetNewsUpdates())
.ReturnsAsync("{your desired return here}");
var controller = new NewsController(newsBusinessLogicMock.Object);
controller.Configuration = new System.Web.Http.HttpConfiguration();
controller.Request = new System.Net.Http.HttpRequestMessage();
// Act
var actionResult = await controller.Get();
//assert
Assert.IsNotNull(actionResult);
}
Upvotes: 2