Field Injection Kills Unit Tests

Spring is loved for Dependency Injection. And who doesn’t love @Autowired, where you can just put this annotation on a variable and Spring intelligently fetches the right bean for you?

However, if you want to perform unit tests on your controllers, using @Autowired is a bad idea. How would you be able to mock your service if it is autowired?

The better practice is to use settings and constructors, and make the variable in constructor final, like this:

public MyController(final MyService svc) { ... }

Now, have fun mocking 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s