MOQ-如何验证静态类的调用和委托? [英] MOQ - How to verify static class call and delegates?
问题描述
我刚刚开始阅读Moq框架,并考虑将其应用于现有代码.我可以提出一个测试用例来验证基本函数调用.但是现在只能将其应用于委托和静态类.
I just started reading on Moq framework and thought of applying it to my existing code. I could come up with a test case to verify basic function calls. But now stuck at applying it to delegates and static classes.
下面是被测系统(SUT)
Below is the system under test (SUT)
public class SUT : ISUT
{
private IInterface1 i1;,
private IInterface2 i2;
public SUT(IInterface1 i1, IInterface2 i2)
{
this.i1 = i1;
this.i2 = i2;
}
public void FunctionToTest(Action<string> someDelegate, Action otherDelegate)
{
var list = i2.GetList();
foreach(var r in list)
{
i1.SomeFunction(r);
if(someDelegate != null)
someDelegate("message");
SomeHelper.LogData(r);
}
if(otherDelegate != null)
otherDelegate();
}
}
我的测试设置如下
[TestFixture]
public class when_list_contains_atleast_one_item
{
ISUT sut;
Mock<IInterface1> mockI1;
Mock<IInterface2> mockI2;
public SUT_Tester()
{
mockI1 = new Mock<IInterface1>();
mockI2 = new Mock<IInterface2>();
sut = new SUT(mockI1.Object, mockI2.Object);
}
[Test]
public void it_should_call_somefunction_calldelegates_and_log_data()
{
var dummyList = new List<string> { "string1", "string2" };
mockI2.Setup(m2 => m2.GetList()).Returns(dummyList).Verifiable();
sut.FunctionToTest(It.IsAny<Action<string>>(), It.IsAny<Action>());
// How to verify delegates were raised
// How to verify SomeHelper.LogData was called
mockI1.Verify(m => m.SomeFunction(It.IsAny<string>()), Times.Exactly(2));
mockI2.Verify();
}
}
如何验证someDelegate和otherDelegate是否已提出?SomeHelper是静态类,而LogData是静态函数.如何验证LogData是否被调用?
How to verify that someDelegate and otherDelegate were raised ? SomeHelper is a static class and LogData is a static function. How to verify that LogData was called?
下面是SomeHelper类
Below is the SomeHelper class
public static class SomeHelper
{
static ILogger logger = LoggerManager.GetLogger("Something");
public static void LogData(string input)
{
logger.Info(input);
}
}
推荐答案
- 您无法验证静态方法,因为Moq无法模拟它们.
-
为了验证对委托的调用,请创建它们,以便它们调用本地函数,然后保留状态并验证:
- You cannot verify static methods since they cannot be mocked by Moq.
In order to verify calls on the delegates, create them so that they call a local function and you keep the state and verify:
string localString = string.Empty;
Action< string>动作=(字符串s)=>localString = s;
//...传递给测试
声明.(localString =="TheStringItMustbe");
确定检查没有参数的动作,增加局部变量并断言是否已增加(或类似的东西):
OK to check an action that has no in params, increment a local variable and assert if it has been incremented (or something similar):
int localVar = 0; Action action = () => localVar++; // ... pass it to the test Assert.(localVar == 1);
这篇关于MOQ-如何验证静态类的调用和委托?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!