Why doesn't Times.Always exist in Moq?

Using Moq, you can verify that a method has never been called with specific arguments (that is, arguments that satisfy certain predicates) using Times.Never .

But how to verify that how many temporary methods are called, they are always called with certain arguments?

The default is Times.AtLeastOnce .

No Times.Always . Am I missing something? Thanks!

Edit: Last week I sent the offer to the Moq mailing list, but so far it doesn't seem to be moderated. I will post any updates here.

Edit: example. Let's say I'm testing a class that generates XML documents. I want only valid documents to be created. In other words, verify that the writer’s dependency only ever produced valid documents with a valid record number.

 should_only_write_valid_xml_documents Mock.Get(this.writer).Verify( w => w.Write( It.Is<XDocument>(doc => XsdValidator.IsValid(doc)), It.Is<int>(n => n < 3)), Times.Always); 
+6
source share
4 answers

It looks like you want a “Strictly” behavior layout. If the method is called with anything other than the expected parameters, the test will fail.

This is available in Moq:

 var mock = new Mock<IFoo>(MockBehavior.Strict); 

(Example taken from Moq QuickStart .)

Each layout reference should now have a corresponding Setup .

Using rigorous layouts tends to lead to fragile trials. I would avoid this technique, or at least use it sparingly.

+3
source

And how many times "always"? Moq keeps track of all times when a particular method is called with specific arguments, and then uses that number to compare with Times.Never, Times.AtLeastOnce, etc.

So, if the method is executed 4 times and you set it to "Times.Always", what does this mean?

Times.Never will check to make sure the number is zero.

Times.AtLeastOnce will verify that the number is greater than or equal to one.

Times.Always will verify that the number ...?

You can determine the number of times it MUST start programmatically, and then do something like:

 Times.Exactly(calculatedAmount) 

But Mok does not know what "always" means.

+8
source

You can apply logic inversion to check ALWAYS.

eg:.

Suppose you want to perform the following check:

 mock.Verify(x => x.Method(It.Is<int>(i => i == 10)), Times.Always()); 

you can just replace it:

 mock.Verify(x => x.Method(It.Is<int>(i => i != 10)), Times.Never()); 
+2
source

My recommendation would be to create a “fallback” match for a method with It.IsAny conditions. You can then check Times.Never on this mapping, which should always be replaced with a more specific match.

0
source

Source: https://habr.com/ru/post/906216/


All Articles