Moq how determine a method was called with a list containing certain values [duplicate]

大城市里の小女人 提交于 2019-12-08 15:50:07

问题


Hi say I have a method with the following signature:

public void GeneratePaymentAdvise(IList<int> paymentIds)

and this is called by another method:

public void UpdatePaymentStatus(IList<int> paymentIds, IPaymentLogic paymentLogic)
{
 ...
   paymentLogic.GeneratePaymentStatus(paymentIds);
 ...
}

So in a unit test I want to make sure this was called. Using moq:

var mockPaymentLogic = new Mock<PaymentLogic>();

UpdatePaymentStatus(new List<int> { 2, 3 }, mockPaymentLogic.Object);

mockPaymentLogic.Verify(x => x.GeneratePaymentStatus(It.IsAny<IList<int>>());

So this would work fine and checks that GeneratePaymentStatus is called but only that was called with any old list of ints.

Is there a way to rewrite this so it tests that GeneratePaymentStatus was called with a list of ints containing 2 and 3?


回答1:


Something like that:

mockPaymentLogic.Verify(x => x.GeneratePaymentStatus(It.Is<IList<int>>(l => l.Contains(2) && l.Contains(3))));



回答2:


Why don't you just use the same int array for verification.? Something like this..

[TestClass]
public class SomeClassTests
{
    [TestMethod]
    public void UpdatePaymentStatus_PaymentIds_VerifyPaymentLogicGeneratePaymentStatus() {
        var mock = new Mock<IPaymentLogic>();
        var sut = new Sut();
        var idList = new List<int> {2, 3};

        sut.UpdatePaymentStatus(idList, mock.Object);

        mock.Verify(x => x.GeneratePaymentStatus(idList));
    }
}

public class Sut {
    public void UpdatePaymentStatus(IList<int> paymentIds, IPaymentLogic paymentLogic) {
        paymentLogic.GeneratePaymentStatus(paymentIds);
    }
}

public interface IPaymentLogic {
    void GeneratePaymentStatus(IList<int> paymentIds);
}

If you verify against a different list other than idList, the test would fail.



来源:https://stackoverflow.com/questions/17144441/moq-how-determine-a-method-was-called-with-a-list-containing-certain-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!