Skip to content

How to test a controller with the validation at Spring Boot 1.4+ #6658

Closed
@WildDev

Description

@WildDev

Question

Spring Boot 1.4 has a number of fine features including @DataJpaTest annotation that automatically wakes up the classpath embedded database for the test purposes. As far I know, it won't work in conjuction with TestRestTemplate in bounds of the same class.

The following test won't work:

@RunWith(SpringRunner.class)
@SpringBootTest
@DataJpaTest
public class PersonControllerTest {

    private Logger log = Logger.getLogger(getClass());

    private Category category;

    @Autowired
    private TestRestTemplate restTemplate;

    @Autowired
    private TestEntityManager entityManager;

    @Before
    public void init() {

        log.info("Initializing...");

        category = entityManager.persist(new Category("Staff"));
    }

    @Test
    public void personAddTest() throws Exception {

        log.info("PersonAdd test starting...");

        PersonRequest request = new PersonRequest("Jimmy");

        ResponseEntity<String> response = restTemplate.postForEntity("/Person/Add", request, String.class);
        assertEquals(HttpStatus.OK, response.getStatusCode());

        log.info("PersonAdd test passed");
    }

During startup of the test an exception will be thrown:

Unsatisfied dependency expressed through field 'restTemplate': No qualifying bean of type [org.springframework.boot.test.web.client.TestRestTemplate]

Then guessing to switch to the recommended mock based slice approach but it won't work there because the controller looks like this:

@RequestMapping(value="/Person/Add", method=RequestMethod.POST)
public ResponseEntity personAdd(@Valid @RequestBody PersonRequest personRequest, Errors errors) 

     personValidator.validate(personRequest, errors):

     if (errors.hasErrors())
         return new ResponseEntity(HttpStatus.BAD_REQUEST);

     personService.add(personRequest);

     return new ResponseEntity(HttpStatus.OK);
}

... it's easy to mock the personService as the documentation suggests but how to be with the errors object which is not mockable in this case? As far I know, there's no ways to mock it since it isn't class field or a returned value of a method.

So, I'm unable to test the code above using neither slice approach nor integration one since @DataJpaTest should not be used with a controller.

Is there a way to test the controller with such architecture using Spring Boot 1.4 testing features?

Metadata

Metadata

Assignees

No one assigned

    Labels

    for: stackoverflowA question that's better suited to stackoverflow.com

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions