【问题标题】:How to unit test, actionresult with using mysql in ASP.NET Core如何在 ASP.NET Core 中使用 mysql 进行单元测试和操作结果
【发布时间】:2021-06-05 05:17:30
【问题描述】:

如何使用 mysql 的操作结果来测试这段代码?

    [HttpPost]
    public ActionResult SomeAction(string qrcode)
    {
        string connectionString = @"Server=localhost;Database=aspkladovaya;Uid=root;Pwd=qwerty98123;";
        string result = "";

        try
        {
            using (MySqlConnection sqlCon = new MySqlConnection(connectionString))
            {
                try
                {
                    int userID = Convert.ToInt32(qrcode);
                    sqlCon.Open();

                    MySqlDataAdapter sqlDa = new MySqlDataAdapter("UserFindByID", sqlCon);
                    sqlDa.SelectCommand.Parameters.AddWithValue("_qruserid", userID);
                    sqlDa.SelectCommand.CommandType = CommandType.StoredProcedure;

                    DataTable dtbl = new DataTable();
                    sqlDa.Fill(dtbl);

                    for (int i = 0; i < 3; i++)
                    {
                        if (qrcode == dtbl.Rows[i][1].ToString())
                        {
                            user.QrUserId = qrcode;
                            result = dtbl.Rows[i][3].ToString();
                        }
                        else
                        {
                            result = error;
                        }
                    }
                }
                catch
                {
                }
            }
        }
        catch
        {
        }

        return Json(result);
    }

我想写点东西,但没有任何效果

    [TestMethod]
    public void TestMethod2()
    {
        HomeController homeController = new HomeController();
        ActionResult result = homeController.SomeAction("12");
        Assert.IsInstanceOfType(result, typeof(ViewResult));
    }

我收到这样的错误

Assert.IsInstanceOfType 失败。预期类型:。实际类型:

【问题讨论】:

    标签: c# unit-testing asp.net-core


    【解决方案1】:

    您的测试方法应如下所示。

     [TestMethod]
        public void TestMethod2()
        {
            HomeController homeController = new HomeController();
            ActionResult result = homeController.SomeAction("12");
            Assert.IsInstanceOfType(result, typeof(JsonResult));
        }
    

    您的方法正在返回 JsonResult,您正在尝试检查它是否为 ViewResult。这就是问题的原因。

    【讨论】:

      猜你喜欢
      • 2017-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-04
      • 2017-05-28
      相关资源
      最近更新 更多