我刚刚开始阅读 Moq 框架,并考虑将其应用到我现有的代码中。我可以提出一个测试用例来验证基本函数调用。但现在坚持将其应用于委托和静态类。
以下是被测系统 (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是否被调用?
下面是 SomeHelper 类
public static class SomeHelper
{
static ILogger logger = LoggerManager.GetLogger("Something");
public static void LogData(string input)
{
logger.Info(input);
}
}
- 您无法验证静态方法,因为它们无法被 Moq 模拟。
-
为了验证对委托的调用,请创建它们,以便它们调用本地函数,并且您保留状态并验证:
string localString = string.Empty;
Action<string> action = (string s) => localString = s;
// ... pass it to the test
Assert.(localString == "TheStringItMustbe");
(UPDATE)
可以检查参数中没有的操作,增加局部变量并断言它是否已增加(或类似的东西):
int localVar = 0;
Action action = () => localVar++;
// ... pass it to the test
Assert.(localVar == 1);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)