Catching both default and non-default inputs

Hey,

I figured I’d give Diffblue Cover a try on a Spring Boot project, because setting up tests/mocking/etc… is pretty tedious. When I wrote a test on super basic tutorial example https://spring.io/guides/gs/serving-web-content/, specifically this controller

package com.example.servingwebcontent;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class GreetingController {

	@GetMapping("/greeting")
	public String greeting(@RequestParam(name="name", required=false, defaultValue="World") String name, Model model) {
		model.addAttribute("name", name);
		return "greeting";
	}

}

I was surprised that a test was created only for the default case, and not the case where an explicit argument is provided (/greeting?name=test). Any way to get test that cover both cases?

Cheers!

Hi,
Cover doesn’t test the various combinations of required and default request parameters as this will primarily test Spring’s built-in functionality and not your own code.

Cover will only provide an optional parameter when it has to, for example if the default value is insufficent to exercise certain functionality in your code. For example, Cover will produce two tests if your code was:

@GetMapping("/greeting")
public String greeting(@RequestParam(name="name", required=false, defaultValue="World") String name, Model model) {
  if (!name.equals("World")) {
    name = "dear " + name;
  }
  model.addAttribute("name", name);
  return "greeting";
}

because it will also attempt to cover the if branch.

To reach deeper into the bag of tricks, you could simply trick Cover into producing a test with a different argument value by adding a temporary assertion:

@GetMapping("/greeting")
public String greeting(@RequestParam(name="name", required=false, defaultValue="World") String name, Model model) {
  assert !name.equals("World"); // <-- remove this after writing the test
  model.addAttribute("name", name);
  return "greeting";
}

But in your case, just making the request parameter required for the time of producing the test will have the same effect.

Do you think producing more combinations of required and default request parameters is a feature we should consider?