lundi 1 février 2016

How to set value to a local variable of a class using NSubstitute in TestProject?

I need to mock with NSubstitute and need to set local variable 'command' of a class LoanCreateHandler to mock data with it's parameter Z. I have code like give below:

Public class ClassA{
  public string Prop1 { get; set; } 
  public string Prop2 { get; set; } 
  … // Here I have some other properties
}

Public class CreateLoanCommand{
  public string X { get; set; } 
  public string Y { get; set; } 
  public ClassA Z { get; set; } 
}    

public class LoanCreateHandler    {       

    public Response Handle(LoanCreateRequest request)
    {
        var response = CreateTypedResponse();
        var command = new CreateLoanCommand
        { 
          X = request.X,
          Y = request.Y
        };

        _cqsCommandProcessor.Execute(command); //here I am setting value of command.Z param

        if (command.Z == null)
        {
          //do something
        }else{
          //do another
        }

        return true; // returns response 
    }

So here when I want to mock LoanCreateHandler for code coverage. Else loop code is not getting covered. Please find unit test below:

[TestClass]
    public class LoanCreateHandlerTests
    {
[TestMethod, TestCategory(Tc.Unit)]
        public void LoanCreateHandler_SuccessTest()
        {
            var loanCreateRequest = new LoanCreateRequest
            { 
                    X = “val1”,
                    Y = “val2”                                    
            };
            var loanCreateResponse = true;


            var createLoanCommand = new CreateLoanCommand()
            {
                X = “val1”,
Y = “val2”,
Z = new ClassA()
{
    Prop1 = “val1”, Prop2 = “val2”…
}
            };

            _TestHelper.CqsCommandProcessor.Execute(Arg.Any<CreateLoanCommand>());

            var loanCreateHandler = new LoanCreateHandler();
            loanCreateHandler.Handle(loanCreateRequest).Returns(loanCreateResponse);
//here when call goes to Handle() method it creates new CreateLoanCommand object and I want to replace that object with my createLoanCommand object, which is created above.

            Assert.IsNotNull(loanCreateResponse);            
        }
}

Aucun commentaire:

Enregistrer un commentaire