check that a function had been called with a certain parameter in unit testing

1.3k Views Asked by At

I'm working with BDDfy, AutoFixture and Moq for my testing.

I want to check that a function had been called with a certain parameter.

The function has a number of parameters which it gets.

Updated This is the given step

 ICollection<string> result = new List<string>();
    _objectMock = new Mock<T>();
    _objectMock.SetupSequence(objectMock =>
     objectMock.Run(It.IsAny<DataModel1>(), It.IsAny<Collection<DataModel2>>())
     .Throws(_customException)
     .Returns(Task.FromResult(result));

On the [Then] part, I check that:

    mock.Verify(mock => mock.verifyData(It.IsAny<DataModel1>(), It.IsAny<IReadOnlyCollection<DataModel2>>()));

I want to check that the 2nd parameter to the function verifyData was of a certain object.

2

There are 2 best solutions below

0
On BEST ANSWER

You could use It.Is<T> for the purpose. For example,

It.Is<string>(c=>c == "Something")

In the particular case you have given in OP, the second parameter could be given as

mock.Verify(mock => mock.verifyData(It.IsAny<DataModel1>(), It.Is<IReadOnlyCollection<DataModel2>>(x=> x==expectedParam), It.IsIn<IReadOnlySet<DataModel3>>(), It.IsAny<IReadOnlyCollection<DataModel3>>()))
0
On

Anu Viswan, you are right.

The reason it still didn't work was becuase the parameter was a reference type and I was comparing 2 different refs.

I checked the actual string inside the objects and it solved it.

It.Is<string>(obj=>obj.prop == "Something")