My Shitty Code

Embracing the Messiness in Search of Epic Solutions

Tag: Unit Testing

  • Spring: Component Scan Selected Classes

    PROBLEM Let’s assume we have a package with the following classes where each class is either annotated with Spring’s @Service, @Component, @Controller or @Repository. When writing unit test, we want Spring to component scan class A and class B. SOLUTION Before we begin, we configure Log4j to log Spring in debug level. Step 1 If […]

  • Java: Promoting Testability by Having Enum Implementing an Interface

    OVERVIEW This post illustrates how we can easily write a better test case without polluting our production code with non-production code by performing a minor refactoring to the production code. PROBLEM Let’s assume we have a simple Data Reader that reads all the lines of a given algorithm data file and returns them:- This API […]

  • MockMvc : Circular view path [view]: would dispatch back to the current handler URL [/view] again

    PROBLEM Let’s assume we want to test this controller:- Here’s the test file:- When executing this test, we get the following error:- SOLUTION The reason this is happening is because the uri “/help” matches the returned view name “help” and we didn’t set a ViewResolver when constructing the standalone MockMvc. Since MockMvcBuilders.standaloneSetup(…) doesn’t load Spring […]

  • MockMvc + Mockito = Epic Tests

    Spring Framework 3.2 introduces a very elegant way to test Spring MVC controller using MockMvc. Based on the documentation, there are two ways to configure MockMvc:- The first approach will automatically load the Spring configuration and inject WebApplicationContext into the test. The second approach does not load the Spring configuration. While both options work, my […]

  • How to Unit Test Spring MVC Controller

    SCENARIO Let’s assume we have the following controller that needs to be tested:- SOLUTION 1: “Works but It Won’t Get You the Promotion” This working solution relies on:- While this solution works, but it has a few problems. This test case strictly tests the actual controller API, but it completely disregards the URI and request […]