Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking objects in JUnit tests - best practice? [closed]

Do you think mocking objects in JUnit test is a bests practice? I don't see the big advantage. Sure if you have a database which should not be considered in your test it makes sense, but why isn't just injected an other implementation of that component (if spring is used). An object factory for the tests would make this much easy. I don't have much experience (we are using Mockito), but I've already seen, that application code gets modified so that some properties gets mockable! Test cases should never efford such changes in productive code in my oppinion.

So what do you think of this topic? In which cases do you are mocking your object or why you don't?

like image 865
Kai Avatar asked May 04 '11 08:05

Kai


People also ask

Should I mock everything in unit tests?

In a unit test, mock objects can simulate the behavior of complex, real objects and are therefore useful when it is impractical or impossible to incorporate a real object into a unit test. Mocking makes sense in a unit testing context.

Is mocking good practice?

Mocking isn't just about isolating the code under test—it's also about creating faster and simpler tests. But, if you don't do it right, mocking can also just generate more code for you to manage and maintain. Best practices with mocking tools ensure that all your mocks add value to your testing without adding cost.

How do you mock an object in JUnit?

We can use Mockito class mock() method to create a mock object of a given class or interface. This is the simplest way to mock an object. We are using JUnit 5 to write test cases in conjunction with Mockito to mock objects.


1 Answers

I've already seen, that application code gets modified so that some properties gets mockable! Test cases should never efford such changes in productive code in my oppinion.

The core idea of TDD is that by forcing you to make all your code testable, the design in general will become better. This doesn't necessarily mean just to have everything mockable, it could also mean reducing coupling so that less mocking is necessary.

Even if you don't agree with that philosophy (I don't buy it 100% myself), as long as you believe that automated tests provide value, then changing the production code to support that value makes sense (unless it seriously compromises the design in some other way).

like image 165
Michael Borgwardt Avatar answered Oct 29 '22 12:10

Michael Borgwardt