[英]How can I assert that a particular method was called using NUnit?
如何測試由於測試而使用正確的參數調用特定方法? 我正在使用NUnit 。
該方法不返回任何內容。 它只是寫在一個文件上。 我正在使用System.IO.File
的模擬對象。 所以我想測試函數是否被調用。
您必須使用一些模擬框架,例如Typemock或Rhino Mocks或NMocks2 。
NUnit也有一個Nunit.Mock ,但它並不為人所熟知。
moq的語法可以在這里找到:
var mock = new Mock<ILoveThisFramework>();
// WOW! No record/reply weirdness?! :)
mock.Setup(framework => framework.DownloadExists("2.0.0.0"))
.Returns(true)
.AtMostOnce();
// Hand mock.Object as a collaborator and exercise it,
// like calling methods on it...
ILoveThisFramework lovable = mock.Object;
bool download = lovable.DownloadExists("2.0.0.0");
// Verify that the given method was indeed called with the expected value
mock.Verify(framework => framework.DownloadExists("2.0.0.0"));
另外,請注意,您只能模擬接口 ,因此如果您的System.IO.File
中的對象沒有接口,那么您可能無法做到。 您必須將您對System.IO.File
的調用包裝在您自己的自定義類中。
需要更多背景。 所以我會在這里添加一個Moq:
pubilc class Calc {
public int DoubleIt(string a) {
return ToInt(a)*2;
}
public virtual int ToInt(string s) {
return int.Parse(s);
}
}
// The test:
var mock = new Mock<Calc>();
string parameterPassed = null;
mock.Setup(c => x.ToInt(It.Is.Any<int>())).Returns(3).Callback(s => parameterPassed = s);
mock.Object.DoubleIt("3");
Assert.AreEqual("3", parameterPassed);
通過使用模擬接口。
假設您的類ImplClass
使用接口Finder
並且您希望確保使用參數“hello”調用Search
函數;
所以我們有:
public interface Finder
{
public string Search(string arg);
}
和
public class ImplClass
{
public ImplClass(Finder finder)
{
...
}
public void doStuff();
}
然后你可以為你的測試代碼編寫一個mock
private class FinderMock : Finder
{
public int numTimesCalled = 0;
string expected;
public FinderMock(string expected)
{
this.expected = expected;
}
public string Search(string arg)
{
numTimesCalled++;
Assert.AreEqual(expected, arg);
}
}
那么測試代碼:
FinderMock mock = new FinderMock("hello");
ImplClass impl = new ImplClass(mock);
impl.doStuff();
Assert.AreEqual(1, mock.numTimesCalled);
在Rhino Mocks中,這是一個名為AssertWasCalled的方法
這是一種使用它的方法
var mailDeliveryManager = MockRepository.GenerateMock<IMailDeliveryManager>(); var mailHandler = new PlannedSending.Business.Handlers.MailHandler(mailDeliveryManager); mailHandler.NotifyPrinting(User, Info); mailDeliveryManager.AssertWasCalled(x => x.SendMailMessage(null, null, null), o => o.IgnoreArguments());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.