Moq的使用心得

  1. 1.Moq中Mock Repository时最好是Mock Repository的接口,这样会避免不知名的错误。

    var mockClubRepository = new Mock<IClubRepository>();
    
    mockClubRepository.Setup(mr => mr.GetById(It.IsAny<Guid>()))

    2.Moq 中怎样返回空(How to return null in Moq):

    mockRepository.Setup(mr => mr.GetItems()).Returns(() => null);

    这种写法很常用,比如返回一个空的List

    mockRepository.Setup(mr => mr.GetItems()).Returns(() => new List<Object>);

    3.怎样Mock一个IsValid == false 的ModelState。

    很简单:UsersController.ModelState.AddModelError("username","Bad username"); 添加个ModelError就可以改变ModelState的IsValid属性了。

    4.How to Mock User.Identity.Name

    Testing controller Action that uses User.Identity.Name

    ControllerCreateControllerForUser(string userName)
    {
        var mock = newMock<ControllerContext>();
        mock.SetupGet(p => p.HttpContext.User.Identity.Name).Returns(userName);
        mock.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true);
     
        var controller = newSomeController();
        controller.ControllerContext = mock.Object;
     
        return controller;
    }

    5. 有时候需要单元测试文件上传,那么怎么去Mock一个上传的文件呢?

    原理很简单,只需要MockHttpContext.Request.Files的一些需要的属性即可,例如:

    在ASP.NET MVC中,上传的文件都是放在HttpPostedFileBase这个对象中,我们可以直接Mock这个对象,对保存文件的方法进行单元测试

    [TestMethod]

    public void TestUpLoadFile()

    {

    var mockFile = new Mock<HttpPostedFileBase>();

    mockFile.Setup(d => d.FileName).Returns("test.txt");

    mockFile.Setup(d => d.ContentLength).Returns(100);

    mockFile.Setup(d => d.InputStream).Returns(new MemoryStream());

    const string uploadsFolder = "D:\\UploadedFiles";

    Domain.DMS.File file = _fileService.UploadedFile(mockFile.Object, uploadsFolder);

    Assert.AreEqual("test.txt", file.FileName);

    Assert.AreEqual(100, file.FileSize);

    Assert.AreEqual("txt", file.FileExtension);

    }

      

 
 
 
标签: ToolMoq
05-11 04:56