2010-09-16 6 views
9

In meinen Komponententests mache ich eine geschützte Methode mit Moq und möchte behaupten, dass sie eine bestimmte Anzahl von Malen aufgerufen wird. This question beschreibt etwas ähnliches für eine frühere Version von Moq:Überprüfen Sie, wie oft eine geschützte Methode mit Moq aufgerufen wird

//expect that ChildMethod1() will be called once. (it's protected) 
testBaseMock.Protected().Expect("ChildMethod1") 
    .AtMostOnce() 
    .Verifiable(); 

... 
testBase.Verify(); 

aber das funktioniert nicht mehr; die Syntax hat sich seitdem verändert, und ich kann das neue Äquivalent unter Verwendung Moq 4.x nicht gefunden:

testBaseMock.Protected().Setup("ChildMethod1") 
    // no AtMostOnce() or related method anymore 
    .Verifiable(); 

... 
testBase.Verify(); 

Antwort

17

Im Moq.Protected Namespace gibt es eine IProtectedMock Schnittstelle, die eine Verify-Methode nimmt Zeiten als Parameter hat.

Bearbeiten Dies ist seit mindestens Moq 4.0.10827 verfügbar. Syntax Beispiel:

testBaseMock.Protected().Setup("ChildMethod1"); 

... 
testBaseMock.Protected().Verify("ChildMethod1", Times.Once()); 
4

erweitern Ogata Antwort können wir auch eine geschützte Methode überprüfen, die Argumente nimmt:

testBaseMock.Protected().Setup(
    "ChildMethod1", 
    ItExpr.IsAny<string>(), 
    ItExpr.IsAny<string>()); 

testBaseMock.Protected().Verify(
    "ChildMethod1", 
    Times.Once(), 
    ItExpr.IsAny<string>() 
    ItExpr.IsAny<string>()); 

Zum Beispiel, das wäre ChildMethod1(string x, string y) zu überprüfen.

Siehe auch: http://www.nudoq.org/#!/Packages/Moq.Testeroids/Moq/IProtectedMock(TMock)/M/Verify

Verwandte Themen