简体   繁体   English

使用Moq进行单元测试

[英]Unit Testing using Moq

This is a method under my controller which is used to create dummy keys to encrypt the data in the application and store the same in the amazon s3 bucket. 这是在我的控制器下的一种方法,该方法用于创建伪密钥以对应用程序中的数据进行加密并将其存储在Amazon s3存储桶中。

public JsonResult SaveMasterKeys(string MekText, int Thismek)
        {
            string folderName = string.Empty, fileName = string.Empty;
            List<string> folderNameList = new List<string>();
            folderNameList.Add("Guard1");
            folderNameList.Add("Guard2");
            try
            {
                if (Thismek == 1)
                {
                    folderName = "Guard1";
                    fileName = "NewMek1.key";
                }
                else
                {
                    folderName = "Guard2";
                    fileName = "NewMek2.key";
                }
                AWSS3File aws = new AWSS3File();

                //aws.BucketExist(filePath);
                //aws.CreateFile(MekText, filePath);
                // Check Weather the Folder is exist or not

                if (!aws.CheckFolderExist(folderName))
                {
                    foreach (var item in folderNameList)
                    {
                        aws.CreateFolder(item);
                        if (item == "Guard1")
                        {
                            aws.CreateFileIntoS3((item == folderName ? MekText : ""), item, "NewMek1.key");
                            aws.CreateFileIntoS3("", item, "Mek1.key");
                        }
                        else
                        {
                            aws.CreateFileIntoS3((item == folderName ? MekText : ""), item, "NewMek2.key");
                            aws.CreateFileIntoS3("", item, "Mek2.key");
                        }
                    }
                }
                else
                {
                    aws.CreateFileIntoS3(MekText, folderName, fileName);
                }
                ViewData["SaveMessage"] = "Saved successfully.";
            }
            catch (Exception ex)
            {
                XTP.Logger.LogCritical("XTP.Web.internaltools", ex.ToString());
                ViewData["SaveMessage"] = "Keys not updated successfully.";
            }
            return Json(new { success = true, value = ViewData["SaveMessage"] }, JsonRequestBehavior.AllowGet);
        }

And this is the TESTMETHOD I have written for the same 这是我为同一篇写的TESTMETHOD

[TestMethod]
        public void MockAlways()
        {
            var mock = new Mock<AccountController>();
            JsonResult json = new JsonResult();
            //new { success = true, value = ViewData["SaveMessage"] }, JsonRequestBehavior.AllowGet
            json.Data = new { success = true, value = "sa" };
            json.JsonRequestBehavior = JsonRequestBehavior.AllowGet;


            mock.Setup(x => x.SaveMasterKeys("ss", 1)).Returns(json);

            var controller = new AccountController();
            var result = controller.SaveMasterKeys("ss", 1) as JsonResult;

            Assert.AreEqual(mock.Object.SaveMasterKeys("ssxs", 1), result.Data.ToString());
        }

I am getting an invalid setup error. 我收到无效的安装错误。 Is there a way to resolve this error? 有没有办法解决此错误?

I think that you misunderstood how to mock a controller's action. 我认为您误解了如何模拟控制器的动作。 You are mocking it and then comparing it with the mocked controller. 您正在模拟它,然后将其与模拟的控制器进行比较。 This is not a way to go(it is like checking whether true == true . 这不是可行的方法(就像检查true == true

Basically this error means that Moq cannot override non-virtual member(it is self-explanatory). 基本上,此错误意味着Moq无法覆盖非虚拟成员(这是不言自明的)。 You should change method's signature to virtual to allow overriding it. 您应该将方法的签名更改为virtual以允许覆盖它。

But - you shouldn't mock action like this. 但是-您不应该嘲笑这样的动作。 Instead you should mock its dependencies(services, contexts, gateways etc.) and check whether with known input values you can get expected results without mocking the action itself. 相反,您应该模拟其依赖项(服务,上下文,网关等),并检查是否可以在不模拟动作本身的情况下使用已知的输入值获得预期的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM