如何使用TestProject中的NSubstitute将值设置为类的局部变量?

时间:2016-02-01 12:50:56

标签: c# wcf unit-testing nsubstitute

我需要使用NSubstitute进行模拟,并且需要将类command的局部变量LoanCreateHandler设置为使用它的参数Z来模拟数据。  我的代码如下:

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 
    }
}

所以在这里,当我想模拟LoanCreateHandler代码覆盖时。其他循环代码未被涵盖。请在下面找到单元测试:

[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 LoanCreateRequest object and I want to replace that object with my LoanCreateRequest object, which is created above.

        Assert.IsNotNull(loanCreateResponse);            
    }
}

1 个答案:

答案 0 :(得分:1)

您应该使用When..Do回调来设置void方法。

我假设_TestHelper.CqsCommandProcessor返回LoanCreateHandler._cqsCommandProcessor所做的相同对象。

那就是说,你应该这样做:

[TestClass]
public class LoanCreateHandlerTests
{
    [TestMethod, TestCategory(Tc.Unit)]
    public void LoanCreateHandler_SuccessTest()
    {
        var z = new ClassA()
        {
            Prop1 = "val1",
            Prop2 = "val2"
        };

        _TestHelper.CqsCommandProcessor
            .When(x => x.Execute(Arg.Any<LoanCreateRequest>()))
            .Do(x => x.Arg<LoanCreateRequest>().Z = z);

        var loanCreateHandler = new LoanCreateHandler();
        var loanCreateRequest = new LoanCreateRequest
        {
            X = "val1",
            Y = "val2"
        };
        var loanCreateResponse = loanCreateHandler.Handle(loanCreateRequest);

        Assert.IsNotNull(loanCreateResponse);
    }
}