Category: Programming Language
-
Java: Programmatically Compile and Unit Test Generated Java Source Code
In one of the projects I’m currently working on, I have to write a parser to translate a scripting language into Java code. This tutorial shows how you can unit test the generated Java code. Let’s assume we have JavaCodeGeneratorService that looks something like this:- This service class generates Java source code as one big Read More…
-
Java: Properly Indenting XML String
PROBLEM Let’s assume we want to perform a pretty print on the following XML string:- We have the following code to create a formatted XML string:- However, the generated output looks like just the original XML string:- Why? SOLUTION You may think the above code is wrong, but it is not. Based on the DOM Read More…
-
Guava: Elegant Caching Mechanisms
There are many different ways to implement a caching mechanism. Google’s Guava provides very simple and elegant solutions to do so. OPTION 1: Caching using Supplier If you want to cache just one thing, Supplier should satisfy that requirement. In the above example, we cache all employees for a day. OPTION 2: Caching using LoadingCache Read More…
-
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 Read More…
-
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 Read More…
-
Guava: Elegant Collection Ordering
PROBLEM Java provides a built-in API to sort a list, but it is flat out ugly and prone to error especially when dealing with Comparator. Here’s an example:- Number of puppies killed = 3 … from the if-else statement. SOLUTION A better way to do this is to use Ordering from Guava:- </request,> In this Read More…