gpt4 book ai didi

c# - 最小起订量 - 如何验证静态类调用和委托(delegate)?

转载 作者:行者123 更新时间:2023-11-30 15:09:06 25 4
gpt4 key购买 nike

我刚开始阅读 Moq 框架,并想将其应用到我现有的代码中。我可以想出一个测试用例来验证基本的函数调用。但现在坚持将其应用于委托(delegate)和静态类。

下面是被测系统(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 模拟。
  • 为了验证对委托(delegate)的调用,创建它们以便它们调用本地函数并且您保持状态并验证:

    string localString = string.Empty;

    Action<string> action = (string s) => localString = s;

    // ... pass it to the test

    Assert.(localString == "TheStringItMustbe");

(更新)

确定检查没有输入参数的操作,递增局部变量并断言它是否已递增(或类似的东西):

int localVar = 0;
Action action = () => localVar++;
// ... pass it to the test
Assert.(localVar == 1);

关于c# - 最小起订量 - 如何验证静态类调用和委托(delegate)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4821019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com