Home > database >  mock.setup It.IsAny or It.Is instead new object()
mock.setup It.IsAny or It.Is instead new object()

Time:07-20

How come it´s working with below example?

mock.Setup(p => p.GetUCByOrgNumberAsync(It.IsAny<UCPartyModel>))).ReturnsAsync(new PartyUCBusinessDTO() { Orgnr = "xxxxxxxx" });

But not with:

mock.Setup(p => p.GetUCByOrgNumberAsync(new UCPartyModel())).ReturnsAsync(new PartyUCBusinessDTO() { Orgnr = "xxxxxxxx" });

Data is null in below if I don't use It.IsAny or It.Is

    private IActionResult CreateResult<T>(T data)
    {
        return CreateResult<T>(200, data);
    }

CodePudding user response:

new UCPartyModel() is creating a new instance of your model for setup, so when the mock will be setup, the the object passed vs what is defined in Setup is not same, that's why it is not working. So either you can go with It.IsAny<UCPartyModel> or below approach.

var model = new UCPartyModel();
mock.Setup(p => p.GetUCByOrgNumberAsync(model).ReturnsAsync(new PartyUCBusinessDTO() { Orgnr = "xxxxxxxx" });
 // Your code of invocation.
someBusinessObj.Run(model);

With above you are passing the same instance of object so with that actual Setup method will be invoked.

More details about It.IsAny<TValue>

It matches any value of the given TValue type. You can read about it here

  • Related