From what I've seen there are two ways of verifying a test.

Firstly there is state verification where I might Assert that something == something. Then there is behavioral verification where I might check that a method on a mock gets called X times.

In my mind, I want to test to an interface I don't care how a method was executed or implemented. I care on the outcome or result of the method being called. From my experience, checking whether a method was called on a mock makes my code brittle.

Therefore is verifying methods on a mock were called (or behavioral verification) a best practice?

有帮助吗?

解决方案

Not all tests are created equal.

Many cannot be tested behaviorally because the system under test is not interacting with collaborators and only outcome verification makes sense.

Others cannot be tested by outcome because the system under test does not return a result or have side effects.

For example, if you need to verify that the system under test sent a message to an external system, you can only represent that external system as a mock and the aspect that you want to verify is that your system under test called out to the external system.

I am going to amend that statement to say that you are probably less interested in the fact of having called the external API than you are in what was sent. You still use the mock, but instead of just verifying that a method is called once, you verify that the arguments passed to that method were as expected.

Put another way, verifying behavior is sometimes the only window into a system and can be used to verify state.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top