Tag Archives: Spring Boot

Spring Boot: Map JSON body with root node in @RequestBody

Say you have the following JSON:

{
  "rootNode": {
    "firstValue":"",
    "secondValue":""
  }
}

The class to use for this could look something like this:

public class MyValues {
  private String firstValue;
  private String secondValue;
  ...
}

This class will however not map directly to the JSON above via @RequestBody, and this is because the JSON contains a root node (“rootNode”)

The solution here is to wrap the MyValues class into a “root class” like this:

public class MyValuesWrapper {
  MyValues rootNode;
  ...
}

After this you should be able to parse the request body automatically with @ResponseBody like this:

 @PostMapping(value = "/myValues")
  public int postValues(@RequestBody MyValuesWrapper wrappedRequest) {
  
  // Optional: Unwrap for easier access
  MyValues request = wrappedRequest.getMyValues();
  ...

Hope this helps somebody (or me in the future 🙂 )

Tested on Spring Boot v2.3.8 and Java 11

Spring Boot: Create a “RunAllTests” test class with JUnit 5

I like having an easy way to run all tests in a specific package path. I will here show an example of how to create a “RunAllTests” class to use in Spring Boot 2 and JUnit 5 (Jupiter):

package com.niklasottosson.myapp;

import org.junit.platform.runner.JUnitPlatform;
import org.junit.platform.suite.api.SelectPackages;
import org.junit.runner.RunWith;

/**
 * Test class to run all unit tests.
 */
@RunWith(JUnitPlatform.class)
@SelectPackages("com.niklasottosson.myapp.tests")
public class RunAllTests {
}

This will tell JUnit to search the files in the package described (and below) in the @SelectPackages annotation for tests to run

For Spring Boot 2.3.8 the normal “spring-boot-starter-test” dependency was not enough to get the JUnitPlatform into my app (for the @RunWith annotation), so I had to add the following dependency to my pom.xml:

        <dependency>
            <groupId>org.junit.platform</groupId>
            <artifactId>junit-platform-runner</artifactId>
            <version>1.2.0</version>
            <scope>test</scope>
        </dependency>

After all is in place I can run the RunAllUnitTests class and all selected tests runs

Tested on Spring Boot v2.3.8, IntelliJ v2020.3 and JUnit v5 with JUnitPlattform v1.2.0

Gradle: Integration/GUI test setup example with Spring and Protractor

Setting upp integration tests that depends on background process can be a challenge in Gradle. Here is one solution that I have used:

gradle.build

apply plugin: 'java'

/**
* Handle of the background process (script scope)
*/
Process backendProcess

/**
* Task to start the Spring server
*/
task beforeE2eTests {
  ProcessBuilder builder
  builder = new ProcessBuilder('./gradlew bootRun'.split(' '))
  builder.redirectErrorStream(true)

  doLast {
    println "Starting backend"
    backendProcess = builder.start()

    InputStream sto = backendProcess.getInputStream()
    BufferedReader redr = new BufferedReader(new InputStreamReader(sto))

    /**
    * To prevent Gradle to go to next task before the server has started 
    * we add a loop that finds a specific log line. When that 
    * line appears we are good to go to next task
    */
    def line
    while ((line = redr.readLine()) != null) {
      println line
      if (line.contains("Started WebApplication")) {
        println "Backend is ready"
        break;
      }
    }
  }

  finalizedBy 'afterE2eTests'
}

/**
* Task to stop the Spring server
*/
task afterE2eTests {
  doLast {
    println "Stopping backend"
    backendProcess.destroy()
  }

  mustRunAfter 'testAngularE2e'
}

/**
* Task to start E2E tests
*/
task testAngularE2e(type: Exec) {
  mustRunAfter 'beforeE2eTests'

  /**
  * Run the Protractor tests
  */
  commandLine 'node_modules/.bin/protractor', 'e2e/protractor.conf.js'
}

/**
* Main testing task
*/
testAll {
  dependsOn beforeE2eTests, testAngularE2e
}

Tested on OSX 10.15.0 and Gradle 4.10.2