模拟服务调用对象返回null

本文关键字:返回 null 对象 调用 服务 模拟 | 更新日期: 2023-09-27 18:09:24

你好:)我是使用Moq框架的新手,我有一个问题,正如我将在下面演示的那样,我试图在以会话对象为参数的MVC控制器上Moq服务调用。在我的单元测试框架上,我创建了我的对象,将其设置在服务调用上,我希望将其作为测试对断言的响应的结果。

问题:我试图基于其他解决方案模拟HttpContext,这是有效的,因为在控制器方面,我得到了我在单元测试中设置的值,但在服务调用的SETUP(我有"Mock(MockBehavior.Strict);")时,调试器到达控制器,在实际调用时,我得到一个错误说没有定义SETUP。或者如果我去掉MockBehavior。,控制器上的"model"变量总是返回null,而不是我在Unit Test类上设置的对象。

这是我的简单单位类

[TestClass]
public class SearchControllerTest
{
   #region Variables
   Mock<ControllerContext> _controllerContext;
   Mock<ISearchService> _serviceMock;
   SearchController _controller;
   #endregion
   [TestInitialize]
   public void SetUp()
   {
       // Arrange
       _controllerContext = new Mock<ControllerContext>();
       _serviceMock = new Mock<ISearchService>(MockBehavior.Strict);
       _controller = new SearchController(_serviceMock.Object);
   }
   #region Success Test Cases
   [TestMethod]
   public void SearchListTest()
   {
       string pid = "val1";
       string oid = "val2";
       string lang = "val3";
       string tid = "val4";
       string pattern = "val5";
       DocumentViewModel docModel = SetDocumentViewModel();
       // Bypass
       //_controllerContext.Setup(x => x.HttpContext.Session).Returns(_session.Object);
       _controllerContext.SetupGet(p => p.HttpContext.Session["ProjectId"]).Returns("X");
       _controllerContext.SetupGet(p => p.HttpContext.Session["OverlayId"]).Returns(string.Empty);
       _controllerContext.SetupGet(p => p.HttpContext.Session["ProjectLanguage"]).Returns(string.Empty);
       _controllerContext.SetupGet(p => p.HttpContext.Session["NodeId"]).Returns(string.Empty);
       _controller.ControllerContext = _controllerContext.Object;
       _serviceMock.Setup(x => x.FullTextSearchForAll(pid, oid, lang, tid, pattern)).Returns(docModel);
       // Act
       var result = _controller.SearchList(pid, oid, lang, tid, pattern) as PartialViewResult;
       // Assert
       Assert.AreEqual("#0Id", ((DocumentViewModel)result.Model).Rows[0].UID);
    }
    #endregion
    #region Private
    DocumentViewModel SetDocumentViewModel() 
    {
        return new DocumentViewModel()
        {
            Columns = new Service.QueryResultColumn[]
            {
                new Service.QueryResultColumn
                {
                     Alignment = ServiceConstants.Left, 
                     Index = 0, 
                     Visible = true, 
                     Width = 3, 
                     Header = ServiceConstants.Label
                }
            },
            Properties = new DocumentsInfo[]
            {
                new DocumentsInfo()
                {
                    IsCheckInAllowed = true,
                    IsCheckoutAllowed = true,
                    IsDocumentCheckedOut = false,
                    IsPlaceHolder = false,
                    IsUndoCheckoutAllowed = true,
                    lastVersionUid = "123"
                }
            },
            Rows = new Service.QueryResultRow[]
            {
                new Service.QueryResultRow()
                {
                    Children = null,
                    ExtensionData = null,
                    ImageSource = "Source",
                    Items = new Service.QueryResultItem[]
                    {
                        new Service.QueryResultItem()
                        {
                            ExtensionData = null,
                            ImageSource = "Src",
                            Text = "Txt",
                            UID = "uid"
                        }
                    },
                    UID = "#0Id"
                }
            }
        };
     }
    #endregion
 }

这是我的控制器

 public class SearchController : Controller
 {
    ISearchService _searchService;
    public SearchController(ISearchService searchService) // I use UnityContainer
    {
        _searchService = searchService;
    }
    public PartialViewResult SearchList(string pid, string oid, string lang, string tid, string pattern)
    {
        ViewBag.ProjectId = pid;
        ViewBag.OverlayId = oid;
        ViewBag.ProjectLanguage = lang;
        ViewBag.NodeId = tid;
        ViewBag.Pattern = pattern;
        DocumentViewModel model = null;
        try
        {
            model = _searchService.FullTextSearchForAll(
                Session["ProjectId"] as string,
                Session["OverlayId"] as string,
                Session["ProjectLanguage"] as string,
                Session["ProjectId"] as string,
                pattern
            );
        }
        catch (Exception ex)
        {
            ViewBag.Error = ex.Message;
        }
        // Ajax.OnError() will handle the Custom Exception Error Message
        if (ViewBag.Error != null)
            throw new CustomtException((String)ViewBag.Error);
        return PartialView(model);
    }
 }
感谢你的耐心和时间。祝你今天愉快!

模拟服务调用对象返回null

你已经在方法中设置了一些参数值:

_serviceMock.Setup(x => x.FullTextSearchForAll(pid, oid, lang, tid, pattern)).Returns(docModel);

并尝试将会话变量作为空字符串

_controllerContext.SetupGet(p => p.HttpContext.Session["OverlayId"]).Returns(string.Empty);

永远不会匹配。isany () =

_serviceMock.Setup(x => x.FullTextSearchForAll(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(docModel);

如果它会显示change session setup

我建议为ProjectId等创建const,然后使用它们来设置模拟、验证调用和设置任何对象的状态。这确保了您所期望的值(并且只有您所期望的值)在整个过程中被使用。