【问题标题】:How to fix this System.NullReferenceException in Test class? [duplicate]如何在测试类中修复此 System.NullReferenceException? [复制]
【发布时间】: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


【解决方案1】:

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

appsettings.json

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

【讨论】:

  • 感谢您的回答。我添加了包含连接字符串的 .json 文件,但它仍然不起作用。我错过了一步吗?
  • @Questieme 这里有更多信息stackoverflow.com/a/46270215/4846648
猜你喜欢
  • 2023-03-21
  • 2021-12-29
  • 2015-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-08
  • 1970-01-01
相关资源
最近更新 更多