繁体   English   中英

Moq-指定参数值

[英]Moq - Specify Parameter Value

我正在尝试测试一种方法,该方法依赖于模型中一个字段的值(用作参数)。 我正在寻找有关如何模拟此值的帮助,因此我的单元测试将起作用。
不设置此值,测试将遵循异常的路径。

控制器

public class StatusViewerController : Controller
{
    private IERERepository _ereRepository;

    //Dependency Injection
    public StatusViewerController(IERERepository ereRepository)
    {
        _ereRepository = ereRepository;
    }



    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "RecordID,ClientNumber")] StatusViewerFormViewModel model)
    {
        if (ModelState.IsValid)
        {
            try
            {
                //Send to one of two functions depending on RecordID value 
                if (model.RecordID == null)
                {
                    _ereRepository.StatusViewerInsert(model);
                }
                else
                {
                    _ereRepository.StatusViewerUpdate(model);
                }

                return new HttpStatusCodeResult(HttpStatusCode.OK);
            }
            catch
            {
                throw new HttpException(500, "Internal Server Error");
            }
        }
        else
        {
            throw new HttpException(400, "ModelState Invalid");
        }
    }
}

单元测试

/// <summary>
/// Tests the Edit method for ActionResult return type
/// </summary>
[TestMethod]
public void StatusViewer_Edit_Returns_ActionResult()
{
    //Arrange
    var mockRepository = new Mock<IERERepository>();

    StatusViewerController controller = new StatusViewerController(mockRepository.Object);


    //Act
    //I need to set the value of RecordID here or else this test will fail
    //It will return an exception
    ActionResult result = controller.Edit(It.IsAny<StatusViewerFormViewModel>());


    //Assert
    Assert.IsInstanceOfType(result, typeof(ActionResult));
}

只需创建模型并调用被测方法即可。

您尚未完成的工作就是为控制器设置依赖项。

/// <summary>
/// Tests the Edit method for ActionResult return type
/// </summary>
[TestMethod]
public void StatusViewer_Edit_Returns_ActionResult()
{
    //Arrange
    var mockRepository = new Mock<IERERepository>();
    mockRepository
        .Setup(m => m.StatusViewerInsert(It.IsAny<StatusViewerFormViewModel>())
        .Verifiable();

    var controller = new StatusViewerController(mockRepository.Object);

    var model = new StatusViewerFormViewModel {
        RecordID = "set the value of RecordID here",
        ClientNumber = "Other property value here",
        //...other properties
    };

    //Act
    ActionResult result = controller.Edit(model);


    //Assert
    Assert.IsInstanceOfType(result, typeof(ActionResult));
    mockRepository.Verify();//verify that the repository was called.
}

暂无
暂无

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

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