如何在测试 class 中修复此 System.NullReferenceException?

How to fix this System.NullReferenceException in Test class?

通常,我知道如何修复这种异常。但是,这一次,由于是使用 Test classes,我不确定如何传递正确的参数。

我正在测试的方法是 Update() inside 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 class 是这样的:

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: 'Object reference not set to an instance of an object.' Intersection.Controllers.PhaseController.Configuration.get returned null.

如何在 TestUpdateView() 中插入 Configuration?最好不必实际写下整个连接字符串。

正如其他人对您的问题所评论的那样,模拟 IConfiguration 将是 return 连接字符串的一种方式,并且还可以将您的数据库连接模拟为 return 结果集。不过要回答您的问题:看起来像是针对实时数据库的集成测试,因此您的测试项目将需要具有所需的应用程序设置才能无异常连接。为此,请修改测试项目中的 appsettings.json 文件以包含对应于 "ConnectionStrings:DefaultConnection" 的值。例如:

appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "your connection string"
  },
  // other settings
}