What is it.isAny and what is it.is in Unit mock testing

It.IsAny<T> is checking that the parameter is of type T, it can be any instance of type T. It's basically saying, I don't care what you pass in here as long as it is type of T.

this.ColumnServiceMock.Setup(x => x.GetColumn(It.IsAny<Context>(), It.IsAny<Column>())).Returns(ColumnList);

The above is saying whenever the GetColumn method is called with any parameters (as long as they are type of Context and Column respectively), return the ColumnList.

It.Is<T> allows you to inspect what was passed in and determine if the parameter that was passed in meets your needs.

this.ColumnServiceMock.Verify(x => x.GetColumn(It.Is<Context>(y => y == this.context), It.Is<Column>(y => y.Id == 2)), Times.Once);

The above is asserting that the GetColumn method was called exactly once with the Context parameter equal to this.Context and a Column parameter whose Id property equals 2.

Edit: Revisiting this answer years later with some more knowledge. this.ColumnServiceMock.Verify(x => x.GetColumn(It.Is<Context>(y => y == this.context), It.Is<Column>(y => y.Id == 2)), Times.Once); can be shortened to this.ColumnServiceMock.Verify(x => x.GetColumn(this.context, It.Is<Column>(y => y.Id == 2)), Times.Once);. You don't need to use It.Is to check for reference equality, you can just pass the object directly.


It.IsAny<T>() specifies anything thats of that type.

It.Is<T>() is more specific and takes a lamda to make sure it matches that exactly.

Both are just ways to specify an argument that you don't want to specify exactly when mocking. So for example if the argument is a string name and you don't care about the exact name in your test you can use:

It.IsAny<string>() in your mock specification, which will match any string.

If you always want the name to begin with "S" then you can do

It.Is<string>(x => x.StartsWith("S")) which will only match strings starting with S.