Home > database >  When testing, is it better to Mock or to Instantiate new objects? [closed]
When testing, is it better to Mock or to Instantiate new objects? [closed]

Time:09-17

I was writing some unit tests for my app when I came up with the following question:

What's better, to mock an object or to create a new instance of it?

I'm asking about POJO objects not objects with actual logic.

Thanks

CodePudding user response:

What's better, to mock an object or to create a new instance of it?

What's better? Using the actual behavior of an object, or the behavior of the object as you configured it in the test?

Hopefully, it's pretty obvious that the actual behavior is better. Otherwise you're potentially just testing the implementation of the test, which is no use whatsoever.

In fact, in the worst case, you can configure your mock to do things which could simply never happen in production code. For example, there used to be a bug in Mockito that allowed you to specify that the mock should throw checked exceptions that the method was not allowed to throw.

The Wikipedia article about mocking describes situations in which it is appropriate to use mocking:

If an object has any of the following characteristics, it may be useful to use a mock object in its place:

  • the object supplies non-deterministic results (e.g. the current time or the current temperature);
  • it has states that are difficult to create or reproduce (e.g. a network error);
  • it is slow (e.g. a complete database, which would have to be initialized before the test);
  • it does not yet exist or may change behavior;
  • it would have to include information and methods exclusively for testing purposes (and not for its actual task).

So, mocks have their use, under specific circumstances; but you should always favour the use of the actual implementation where practical.

CodePudding user response:

The mocking technique was specially created for testing. So, if you are testing with JUnit, better option is to use mock objects rather than 'real' instances of your POJO.

  • Related