mardi 28 juin 2016

Moq out parameters

I'm fairly new to using Moq and Nunit for unit testing and I'm having issues with one scenario. What I want is for my mock to have an out parameters which my system under test will then use to decide what action to take.

My system under test is an MVC API controller and in particular I'm trying to test the POST method. I want to return an error message for the object when validation fails.

Here is the method code for the controller:

        public IHttpActionResult Post(Candidate candidate)
    {
        try
        {
            if(candidate==null)
                return BadRequest();

            IEnumerable<string> errors;
            _candidateManager.InsertCandidate(candidate, out errors);

            if (errors!=null && errors.Any())
                return BadRequest(CreateErrorMessage("Invalid candidate: ", errors));

            return CreatedAtRoute("DefaultApi", new {id = candidate.CandidateId}, candidate);

        }
        catch (Exception)
        {
            return InternalServerError();
        }
    }

This is my Unit Test Code:

        [Test]
    [Category("CandidateManagerController Unit Tests")]
    public void Should_Return_Bad_Request_When_Creating_Invalid_Candidate()
    {
        IEnumerable<string> errors = new List<string>() {"error1", "error2"};

        var mockManager = new Mock<ICandidateManager>();
        mockManager.Setup(x => x.InsertCandidate(new Candidate(), out errors)).Callback(()=>GetErrors(errors));

        var sut = new CandidateManagerController(mockManager.Object);

        var actionResult = sut.Post(new Candidate());

        Assert.IsInstanceOf<BadRequestResult>(actionResult);

    }

What I expect is that when _candidateManager.InsertCandidate() is run then the errors variable is populated. However what is happening is that when you step through the controller code errors is null after _candidateManager.InsertCandidate() method is run.

If anyone has any ideas what I'm doing wrong or if what I want to do is not possible using Moq then please let me know.

Thanks

Aucun commentaire:

Enregistrer un commentaire