我需要與NSubstitute模擬,並需要設置LoanCreateHandler
類的局部變量command
模擬數據與它的參數Z
。 我有這樣的代碼在下面給出:如何使用TestProject中的NSubstitute將值設置爲類的局部變量?
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);
}
}
能否請你澄清你的嘲諷哪一類?請注意,不能將'Returns'用於未使用'Substitute.For'創建的對象,也不能使用非虛擬成員(接口成員正常工作,成員標記爲'virtual'的類也如此)。另外,問題中的測試不檢查'LoanCreateHandler' - 它檢查在測試期間創建的布爾變量('loanCreateResponse')是否爲空。 –