【发布时间】:2017-04-04 10:30:55
【问题描述】:
我刚开始在我的 WebApi 项目中使用 Nunit 进行单元测试。
我为我的控制器开发了一个测试用例:
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 控制器:
public class NewsController : ApiController
{
private readonly INewsBusinessLogic _newsBusinessLogic;
public NewsController(INewsBusinessLogic newsBusinessLogic)
{
_newsBusinessLogic = newsBusinessLogic;
}
public async Task<IHttpActionResult> Get()
{
return Ok(await _newsBusinessLogic.GetNewsUpdates());
}
}
当我调试我的测试时,它在 Act 上给了我一个 NullReferenceException 的错误,我非常清楚 What is a NullReferenceException?。但无法弄清楚,为什么会发生这种情况以及如何解决它。
旁注:我没有使用任何 ORM。
【问题讨论】:
-
首先,您将
null变量传递给NewsController构造函数,因为您没有在示例中显示将值分配给_newsBusinessLogic -
你误会了。在测试中,您没有为变量赋值,因此它为空
标签: asp.net-mvc unit-testing asp.net-web-api nunit asp.net-web-api2