mardi 5 juillet 2016

Moq - Specify Parameter Value

I'm trying to test a method, which relies on the value of one of the fields in my model (used as a parameter). I'm looking for help on how to mock this value, so my unit test will work.
Without setting this value, the test will follow the path to the exception.

CONTROLLER

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");
        }
    }
}

UNIT TEST

/// <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));
}

Aucun commentaire:

Enregistrer un commentaire