Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Moq.It.IsAny to test a string starts with something

Is it possible to use Moq to say a method accepts a string that starts with "ABC" for example.

As an example something like this:

logger.Verify(x => x.WriteData(Moq.It.IsAny<string>().StartsWith("ABC")), Times.Exactly(3)); 

That wont compile but hopefully it illustrates my point

like image 484
Jon Avatar asked May 28 '12 09:05

Jon


People also ask

What does it IsAny mean?

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.

How Moq works?

Moq, how it works The idea is to create a concrete implementation of an interface and control how certain methods on that interface responds when called. This will allow us to essentially test all of the paths through code.

Whats is MOQ?

When placing an order with some manufacturers and wholesalers, they may require a minimum order quantity (MOQ). That means sometimes manufacturers, suppliers and wholesalers will turn away some customers if they are not willing or able to meet the minimum order quantity.

What is Moq in c#?

Moq is a mocking framework for C#/. NET. It is used in unit testing to isolate your class under test from its dependencies and ensure that the proper methods on the dependent objects are being called. For more information on mocking you may want to look at the Wikipedia article on Mock Objects.


1 Answers

try:

logger.Verify(x => x.WriteData(Moq.It.Is<string>(str => str.StartsWith("ABC"))), Times.Exactly(3)); 

you can see another example of It.Is:

// matching Func<int>, lazy evaluated mock.Setup(foo => foo.Add(It.Is<int>(i => i % 2 == 0))).Returns(true);  

that comes from Moq documentation: https://github.com/Moq/moq4/wiki/Quickstart

like image 167
eyossi Avatar answered Sep 27 '22 19:09

eyossi