1

I've already read this Q&A but it didn't solve the problem. I'm using Spring Boot 1.4.2.RELEASE and I'm attempting to speed up my tests. Up to this point, I've used @SpringBootTest and I'm testing switching some of these simpler tests to @WebMvcTest.

My controller has the following method which is responding to GET requests.

public ResponseEntity<MappingJacksonValue> fetchOne(@PathVariable Long id, @RequestParam(value = "view", defaultValue = "summary", required = false) String view) throws NotFoundException {
    Brand brand = this.brandService.findById(id);

    if (brand == null) {
        throw new NotFoundException("Brand Not Found");
    }

    MappingJacksonValue mappingJacksonValue = jsonView(view, brand);
    return new ResponseEntity<>(mappingJacksonValue, HttpStatus.OK);
}

My test looks like this:

@RunWith(SpringRunner.class)
@WebMvcTest(BrandController.class)
public class BrandSimpleControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private BrandService brandService;

    @Test
    public void testExample() throws Exception {
        Brand brand = new Brand(1l);
        brand.setName("Test Name");
        brand.setDateCreated(new Date());
        brand.setLastUpdated(new Date());

        when(this.brandService.findById(1l)).thenReturn(brand);

        this.mockMvc.perform(get("/api/brands/1").accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.name", is("Test Name")));
    }
}

When I run this test, I get nothing back in the content. I'm not doing anything significantly different than this guide, so not sure what I'm missing.

I should note that using @SpringBootTest with the exact same controller works as expected.

Community
  • 1
  • 1
Gregg
  • 34,973
  • 19
  • 109
  • 214
  • when(this.brandService.findById(1l)).thenReturn(brand); shouldn't be something like given(this.brandService.findById(1L)).willReturn(new Brand(1l)); ? – Matteo Baldi Dec 06 '16 at 15:27
  • I've tried that as well and it gives me the same results of empty content. – Gregg Dec 06 '16 at 15:28
  • Have you tried to add @AutoConfigureMockMvc after @WebMvcTest? I wrote a unit test for a rest-point for my own project. https://github.com/kometen/SpringBootWorldCities/blob/master/src/test/java/no/gnome/WorldcitiesApplicationTests.java – kometen Dec 06 '16 at 18:01
  • Have you ever try to run the test in debug mode? – ksokol Dec 29 '16 at 18:39
  • Long story short, it had to do with some security stuff. – Gregg Dec 29 '16 at 20:27
  • @Gregg if you still remember what the issue was, could you please [answer your own question](https://stackoverflow.com/help/self-answer)? – flaviut Aug 09 '19 at 00:10

0 Answers0