【问题标题】:NSubstitute set up arg with parameter constructorNSubstitute 用参数构造函数设置 arg
【发布时间】:2021-07-18 18:33:57
【问题描述】:

我们如何使用构造函数参数设置参数?

下面是一个示例用例。

public interface ICalculator
{
    int Add(AddWithValues withValues);
}

public class AddWithValues {
    AddWithValues(int a, int b) {
      A = a;
      B = b;
    }
   
    public int A {get;}
    public int B {get;}
}

calculator = Substitute.For<ICalculator>();
calculator
   .Add(Arg.Is<AddWithValues>(??));

如果 Add 接受 a 和 b 整数,文档会显示如何设置它们。 我不能使用谓词,因为 A 和 B 是只读属性。在这种情况下,我们如何设置 AddWithValues(又是特定的 a 和 b 值)?

【问题讨论】:

    标签: c# unit-testing .net-core xunit nsubstitute


    【解决方案1】:

    如果我正确理解您的问题,我们可以使用谓词来做到这一点:

    calculator
       .Add(Arg.Is<AddWithValues>(x => x.A == 42 && x.B > 10));
    

    如果您在 AddWithValues 上定义相等,您也可以使用它来匹配所需的值:

    calculator
       .Add(new AddWithValues>(42, 21)); // Assuming AddWithValues defines value equality
    

    【讨论】:

    • 这行得通。我想当我尝试时,我可能会尝试分配值而不是在谓词中等同。
    猜你喜欢
    • 1970-01-01
    • 2018-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 2023-02-24
    • 1970-01-01
    相关资源
    最近更新 更多