调用方法时Moq验证属性

时间:2017-05-05 18:14:21

标签: c# unit-testing moq

我正在测试围绕WebClient的包装器。我想在调用UploadString时检查,QueryString属性设置为特定值。整个方法完成后,我不需要检查QueryString值。

mockedWebClient.Setup(w=>w.UploadString("url2","POST","bodyyy")).Return("response");
mockedWebClient.Setup(w=>w.QueryString).Return(new NameValueCollection());

testibject.SomeMethod();

// Verify method was called 
mockedWebClient.Verify(w=>w.UploadString("url2","POST","bodyyy");
// Also verify QueryString is set at the time UploadString is called???

1 个答案:

答案 0 :(得分:1)

<强>回调

使用Callback时,您可以使用Setup方法。例如:

NameValueCollection queryString = new NameValueCollection();

mockedWebClient.Setup(w=>w.QueryString).Return(queryString);

bool isExpected = false;

mockedWebClient
    .Setup(w=>w.UploadString("url2","POST","bodyyy"))
    .Callback(() => isExpected = queryString["SomeKey"] == "SomeValue")
    .Return("response");

testibject.SomeMethod();

Assert.IsTrue(isExpected);