Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one write a good unit test without mocking everything?

I have read that mocking everything is bad.
Test Smell: Everything is mocked
Mock Everything Is a Good Way to Sink

I have also read that unit tests look at a single component whilst Integration tests test an entire system working together.
Writing Great Unit Tests: Best and Worst Practices

This confuses me. As I understand it, to write a proper unit test one needs to isolate a single component by mocking everything but the S.U.T. If one uses real objects throughout the test, doesn't that test become an integration test?

How does one write a good (isolated) unit test without mocking everything?

like image 826
user2818782 Avatar asked Mar 31 '17 06:03

user2818782


1 Answers

Mocking model is a bad smell. You should mock only dependencies that participate to the logic of the tested method, not the data. But even with this simple rule, things are not always obvious.

In some cases, unit testing a method is straight as the method has its own logic rules and has also one or two invocations to a distinct external dependency to perform to complete its logic. In this case mocking seems natural.

In some other cases, unit testing is less obvious as the method to test has very few logic rules. It does in its implementation mainly calls to external dependencies. In this case mocking seems really unnatural as the essential of the test could be mocking. Testing the flow invocations with mocking each call is testing a white box. It s brittle as it doesn't test the method logic behavior.It proves only one thing : that your code does what it does.

In this case, I think that integration tests should be favored over unit tests.

like image 94
davidxxx Avatar answered Oct 14 '22 03:10

davidxxx