Skip to main content

Use Service objects along with your controllers in Spring boot to cleanup code and testing


If you have Spring controller that uses repository objects, it can become a bit messy to write tests with mocks that have to mock various repository object methods like save() etc. Instead, you can use

Here is an example controller that uses repository objects:

@RestController
public class StateManagerController {
    public StateManagerController(XRepository aRepository, YRespository yRepo) {
    }
    public void aMethod() {
       // use xRepo, yRepo : e.g., xRepo.save() , yRepo.delete() etc.
    } 
...
} 



To test methods of this controller that use the repository objects, you will likely have to mock each repository collaborator object. Then you can get into lots of mocking details that make your tests ugly.

Instead, I find that using the following pattern greatly simplifies both your code and tests. It's very simple but works great.

1. In your controller, only inject/depend on @Service objects. Don't use repository objects directly
2. Test your controllers using mocks of these service objects
3. Test your Service objects separately using mocks of the repository objects

For example, the above could be rewritten as:

StateManagerController.java:

@RestController
public class StateManagerController {

    private final AService aService;

    public StateManagerController(AService alertService) {
        this.alertService = alertService;
    }
    public void aMethod() {
        // use aService instead of repo 
    ...
}


AService.java:

@Service
public class AService {

    private final XRepo xRepo;

    public AService(XRepo xRepo) {
        this.xRepo = xRepo;
    }
    public void aMethod() {
        // use xRepo 
    ...
}
 


Now, your tests for StateManagerController become a lot simpler since you just have to mock AService and not worry about repository methods liek save etc


  AService alertService = mock(AService.class);
  when(alertService.updateAlertStatus(1L).thenReturn(1);

  StateManagerController controller = new StateManagerController(aService);

  // exercise  ResponseEntity<?> alertResponse = controller.updateAlert(1L);

  // ensure reponse is correct  assertThat(alertResponse).isEqualTo(ResponseEntity.ok().build());



 
Not only is your testing cleaner, your code organization is also cleaner and you get a lot of reuse from the Service classes that you can use in other controller or non controller objects as well.

Enjoy!


Comments

Popular posts from this blog

Authenticating Spring Boot based application against secure LDAP/AD server

Authenticating against an Active Directory setup is quite common in organizations using Spring Boot / Spring Security can be a pain if you don't know exactly the requirements. I needed to add auth in my web app and secure some but not all endpoints of the application. My story was, I needed Spring security to authenticate against my company LDAP server which uses Active Directory I started by using the standard LDAP guide such as this which are all over the Internet, https://spring.io/guides/gs/authenticating-ldap/ and was able to setup the basic framework However, only test level LDAP auth was working for me, when I tried to auth against the company LDAP secure server, I had to resolve a few issues After 1 week and working with several devs at the company, I finally found why it was not working and the fix was easy Since I spent a week or so resolving this, I wanted to write this up in case someone finds this useful. Here is what I did (it was easy until the fourth ...

Unit testing code that uses environment variables and system properties with fakes

I did not exactly learn this today, but I am sharing it as I have found it extremely useful when unit testing code that depends on environment or system property settings. While I am using Java as an example, the general concepts apply any where. Problem : You have a piece of code you are unit testing that uses settings from env variables or system properties passed to the VM (System.getProperty), but you don't want the tests to be affected by the 'real' environment or system properties in the VM. So, your unit tests should not get different results or fail when the real environment changes. Solution : There are several. But the most straightforward is to use a mocking library to mock out the environment or fake it out, whatever your prefer. You can create a fake using a library like EasyMock, PowerMock etc. This I won't discuss in this post, since there are numerous articles for that. Or you can write a simple class that acts as a proxy, using the proxy pattern...

Using custom conditional logic to enable/disable Spring components

If you have a Spring component and you don't want it to load, you can use Spring's predefined conditionals as much as possible. For example, @Component   @ConditionalOnNotWebApplication   public class SchedulerEntryPoint implements ApplicationRunner { ...  } This will not load your component when running in non web application mode. Such as you may want to start the application but without any of the web framework using SpringApplicationBuilder. But sometimes you want to use custom conditions. It's pretty easy to do so, just use something like this @Component @Conditional (SchedulerCheck. class ) public class SchedulerEntryPoint implements ApplicationRunner { public static class SchedulerCheck implements Condition { @Override public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { return System. getProperty ( "scheduler" ) != ...