【问题标题】:Assert that Fun<T> was invoked断言 Fun<T> 被调用
【发布时间】:2021-08-16 01:53:29
【问题描述】:

给定以下类,我如何测试在调用 MethodUnderTest 时是否调用了 GetSomething

public class SystemUnderTest
{
    private Foo foo;

    public string MethodUnderTest(int input)
    {
       return foo.Get(x => x.GetSomething(input));
    }
}

测试

public void VerifyGetSomethingInvokedWhenMethodUnderTestIsInvoked()
{
   //Arrange
   var sut = new SystemUnderTest();
  
   //Act
   string unusedResult = sut.MethodUnderTest(5);

   //Assert
   A.CallTo(()=> sut.MethodUnderTest(A<int>.Ignored))  //Cant figure out how to test the Func<T> invocation           
   
}

【问题讨论】:

    标签: c# unit-testing fakeiteasy


    【解决方案1】:

    一般来说,用假货进行测试的方法是

    1. 创建一个假对象来抽象出您的被测系统的合作者
    2. 可选择配置假货的行为
    3. 创建被测系统并提供假的
    4. 运行被测系统
    5. 可选择审问假货

    您缺少第 1 部分、第 3 部分(“提供”部分),并且第 5 部分略有偏离。我不知道 x 在您的代码中代表什么,但是您需要伪造它的任何类型,并确保将伪造品提供给 foo 实例。然后你会有类似的东西

    public void VerifyGetSomethingInvokedWhenMethodUnderTestIsInvoked()
    {
       //Arrange
       var fakeX = A.Fake<IX>();
       var sut = new SystemUnderTest(fakeX); // maybe? which would pass it to `foo`?
      
       //Act
       string unusedResult = sut.MethodUnderTest(5);
    
       //Assert
       A.CallTo(() => fakeX.GetSomething(5)).MustHaveHappened();
    }
    

    【讨论】:

    • 谢谢。有时你只需要验证你的想法看起来很长,但这是要走的路。由于实际代码中涉及大量泛型和委托,因此很难生成示例代码。您从我的示例代码中获得了要点,我感谢所有信息。最后我让它工作了。 :)
    猜你喜欢
    • 2018-08-14
    • 2023-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多