【问题标题】:How to verify method parameters with FakeItEasy as well as that a call has been made如何使用 FakeItEasy 验证方法参数以及是否已进行调用
【发布时间】:2016-04-27 01:24:08
【问题描述】:

我正在使用 FakeItEasy 进行一些测试,但遇到了问题。 在测试将预期数据发送到伪造服务时,我也希望能够看到错误数据。 现在我只看到电话从未发生过。 也许我设置错了,但是我想要一些关于如何纠正它的提示。 :)

我的情况是: 两次调用相同的服务,但值不同。 我想要单独的测试来验证每个呼叫。 如果任何参数没有预期值,我想收到一条错误消息,说明这一点。与执行 Assert.AreEqual() 时类似。

现在我只得到“呼叫没有发生”,这是完全可以理解的,因为我意识到这就是我正在测试的。但我希望能够验证一个特定的调用是否只进行了一次,如果没有发生,我想看看使用了哪些值来阻止它发生。

我使用了这个解决方案:http://thorarin.net/blog/post/2014/09/18/capturing-method-arguments-on-your-fakes-using-fakeiteasy.aspx 当我只有一个电话,但有两个电话它不起作用。

 [TestFixture]
public class TestClass
{
    [Test]
    public void TestOne()
    {
        // Arrange
        var fake = A.Fake<IBarservice>();
        var a = new Foo(fake);

        // Act
        a.DoStuff(1);

        //Assert
        A.CallTo(() => fake.DoOtherStuff(A<int>.That.Matches(x => x == 2))).MustHaveHappened(Repeated.Exactly.Once);
    }

    [Test]
    public void TestTwo()
    {
        // Arrange
        var fake = A.Fake<IBarservice>();
        var a = new Foo(fake);

        // Act
        a.DoStuff(1);

        //Assert
        A.CallTo(() => fake.DoOtherStuff(A<int>.That.Matches(x => x == 3))).MustHaveHappened(Repeated.Exactly.Once);
    }
}

public class Foo
{
    private readonly IBarservice _barservice;

    public Foo(IBarservice barservice)
    {
        _barservice = barservice;
    }

    public void DoStuff(int someInt)
    {
        someInt++;
        _barservice.DoOtherStuff(someInt);
        // I should have increased someInt here again, but this is a bug that my tests catches
        _barservice.DoOtherStuff(someInt);
    }
}

public interface IBarservice
{
    void DoOtherStuff(int someInt);
}

【问题讨论】:

    标签: c# fakeiteasy


    【解决方案1】:

    Markus,我有一条评论,因为我犯了一个错误,所以我已经编辑了。

    你说你只得到“电话没有发生”和

    …我希望能够验证一个特定的调用是否只进行了一次,如果没有发生,我想看看使用了哪些值来阻止它发生。

    我担心我不明白你希望得到什么信息,因为当我运行 TestOne 时,我得到了

    FakeItEasy.ExpectationException
    
      Assertion failed for the following call:
        FakeItEasyQuestionsVS2015.IBarservice.DoOtherStuff(<x => (x == 2)>)
      Expected to find it exactly once but found it #2 times among the calls:
        1: FakeItEasyQuestionsVS2015.IBarservice.DoOtherStuff(someInt: 2) repeated 2 times
        ...
    

    这表示调用DoOtherStuff 进行了两次,每次都将someInt 作为值2 传入。

    【讨论】:

      猜你喜欢
      • 2012-07-18
      • 1970-01-01
      • 2011-12-25
      • 1970-01-01
      • 1970-01-01
      • 2018-10-28
      • 1970-01-01
      • 2014-09-15
      • 1970-01-01
      相关资源
      最近更新 更多