【发布时间】:2020-01-08 20:49:47
【问题描述】:
通常,我知道如何修复这种异常。但是,这一次,由于是使用 Test 类,我不确定如何传递正确的参数。
我正在测试的方法是 Update() 在 PhaseController 中。
public IActionResult Update(int id)
{
string connectionString = Configuration["ConnectionStrings:DefaultConnection"];
Phase phase = new Phase();
using (SqlConnection connection = new SqlConnection(connectionString))
{
string sql = $"Select * From Phases Where Id='{id}'";
SqlCommand command = new SqlCommand(sql, connection);
connection.Open();
using (SqlDataReader dataReader = command.ExecuteReader())
{
while (dataReader.Read())
{
phase.Id = Convert.ToInt32(dataReader["Id"]);
phase.Name = Convert.ToString(dataReader["Name"]);
}
}
connection.Close();
}
return View(phase);
}
而我的 PhaseControllerTest 类是这样的:
public class PhaseControllerTest
{
public IConfiguration Configuration { get; }
[Fact]
public void TestCreateView()
{
var controller = new PhaseController(Configuration);
var result = controller.Create() as ViewResult;
Assert.Contains("Create", result.ViewName);
}
[Fact]
public void TestUpdateView()
{
Phase phase = new Phase();
phase.Id = 6009;
phase.Name = "Main Phase";
phase.ReleaseId = 3008;
int id = 6009;
var controller = new PhaseController(Configuration);
var result = controller.Update(id) as ViewResult;
Assert.True(phase.Id == ((Phase) result.Model).Id);
}
}
我得到的错误是在这一行:
string connectionString = Configuration["ConnectionStrings:DefaultConnection"];
说:
System.NullReferenceException: '对象引用未设置为对象的实例。' Intersection.Controllers.PhaseController.Configuration.get 返回 null。
如何在TestUpdateView() 中插入Configuration?最好不要写下整个连接字符串。
【问题讨论】:
-
你在使用模拟库吗?
-
Configuration在测试中为空。没有迹象表明该属性是为测试设置的。要么模拟接口以按预期运行,要么专门为测试创建一个实例 -
@Questieme 这是单元测试还是集成测试?
-
@Questieme 在这种情况下,我再次提醒您当前显示的代码需要重构以准备好进行单元测试。当前代码只能连接到实际连接(集成测试),因为它与实现关注点(实际类)紧密耦合。这似乎是XY problem。
-
@Questieme 查看链接的重复项。
标签: c# asp.net-core asp.net-core-mvc xunit