gpt4 book ai didi

c# - 如何使用 FakeItEasy 伪造 Action <>

转载 作者:太空狗 更新时间:2023-10-30 01:05:11 24 4
gpt4 key购买 nike

我正在使用 FakeItEasy 库为我的单元测试创​​建假对象。

我有一个 ClassUnderTest,我想在其上测试方法 MethodToTest(Data dataObject)。此方法正在调用我想要伪造的接口(interface)的方法:

public interface IFoo
{
void Execute(Action<IDataAccess> action);
}

public class ClassUnderTest
{
private IFoo _foo;

public ClassUnderTest(IFoo foo)
{
_foo = foo;
}

public void MethodToTest(Data dataObject)
{
_foo.Execute(dataAccess => dataAccess.Update(dataObject));
}
}

public interface IDataAccess
{
void Update(Data data);
}

public class Data
{
public int Property { get; set; }
}

在我的单元测试中,我想检查测试方法是否正确调用接口(interface)(使用正确的属性值):

[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var foo = A.Fake<IFoo>(x => x.Strict());
A.CallTo(() => foo.Execute(dataAccess => dataAccess.Update(A<Data>.That.Matches(d => d.Property == 20))));

var cut = new ClassUnderTest(foo);

cut.MethodToTest(new Data { Property = 20 });
}
}

但是在这个测试中有些配置错误。我得到异常:

Test method TestProject1.UnitTest1.TestMethod1 threw exception: FakeItEasy.ExpectationException: Call to non configured method "Execute" of strict fake.

有人知道我必须如何正确配置 CallTo() 语句吗?

最佳答案

更新后的示例确实有帮助,@rhe1980。

首先是关于您提供的测试的一些说明:

  1. A.CallTo方法不执行任何操作 - 它不设置行为(使用 .Invokes.Returns 甚至 .DoesNothing )或验证该方法是否已被调用(例如使用 .MustHaveHappened )。
  2. 比较 Action看起来很难。我确实在 Compare Delegates Action<T> 找到了一些建议,但如果是我,我会采取稍微不同的策略。

而不是尝试比较 Action委托(delegate)给引用模型,我想我可以通过捕获提供给 Execute 的操作来模拟它然后在 IDataAccess 上运行它并查看操作的作用。幸运的是,我们有 FakeItEasy 来帮助解决这个问题!

我在这个测试中取得了成功:

[TestMethod]
public void TestMethod1()
{
// Arrange
var foo = A.Fake<IFoo>(x => x.Strict());

var fakeDataAccess = A.Fake<IDataAccess>();

A.CallTo(() => foo.Execute(A<Action<IDataAccess>>.Ignored))
.Invokes((Action<IDataAccess> action)=>action(fakeDataAccess));

var cut = new ClassUnderTest(foo);

// Act
cut.MethodToTest(new Data { Property = 20 });

// Assert
A.CallTo(() => fakeDataAccess.Update(A<Data>.That.Matches(d => d.Property == 20)))
.MustHaveHappened();
}

希望对你有帮助。

关于c# - 如何使用 FakeItEasy 伪造 Action <>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19974057/

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