模拟服务调用对象返回null

时间:2013-04-16 15:40:54

标签: c# asp.net-mvc unit-testing unity-container moq

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

问题:我尝试基于其他解决方案模拟HttpContext,因为在Controller端我得到了我在单元测试中设置的值,但是在服务调用的SETUP上(我有“Mock(MockBehavior.Strict)”) ;“)当调试器到达控制器时,在实际调用时,我得到一个错误,说没有定义SETUP。或者,如果我取出“MockBehavior.Strict”,控制器上的“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);
    }
 }

坦克你的耐心和时间。 祝你有愉快的一天:)

2 个答案:

答案 0 :(得分:5)

您已使用某些值在方法中设置参数:

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

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

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

永远不会匹配。尝试使用It.IsAny()的设置服务,如

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

如果它会喊出更改会话设置

答案 1 :(得分:0)

我建议为ProjectId等创建consts。 al。,然后使用它们来设置你的模拟,验证调用,并设置任何对象的状态。这样可以确保始终使用您期望的值(并且只使用您期望的值)。