1

I created a test class for SystemAuthorityController, as i only need part of the context to be loaded.

I've used @WebMvcTest annotation and I`ve specified which controller I want to test (I also tried with all controllers but that didn't work either).

@WebMvcTest(SystemAuthorityController.class)
@TestPropertySource("classpath:application.properties")
public class SystemAuthorityControllerTest 

When I try to call any endpoint from this controller I get 404, because the endpoint wasn't found.

After some research I found the solution - that is to add @Import annotation with the controller which I need and everything worked after that, the URL was found.

@WebMvcTest(SystemAuthorityController.class)
@Import({SystemAuthorityController.class})
@TestPropertySource("classpath:application.properties")
public class SystemAuthorityControllerTest 

My question here is why I need to explicitly import the controller I want to test as I never seen this annotation being used for this purpose (neither do I think that I should be used like this). From my understanding WebMvcTest should load all controller beans.

J.F.
  • 13,927
  • 9
  • 27
  • 65

1 Answers1

0

There is no need to explicitly import controller if working in same module.

If you are getting 404, it's probably due to some other reason. [Need to see logs]

This is the basic working example of ControllerTest. [In case you miss anything]

@RunWith(MockitoJUnitRunner.class)
@AutoConfigureMockMvc
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class AControllerTest {
    
    @InjectMocks
    AController aController;
    
    @Autowired
    MockMvc mockMvc;
    
    @Mock
    AService aService;
        
    @Before
    public void setUp() {
        this.mockMvc = MockMvcBuilders.standaloneSetup(aController).build();

    }
    
    @Test
    public void aTest() throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        ADetails user = new ADetails();
        user.setId("1234");
        this.mockMvc.perform(MockMvcRequestBuilders.post("/a/signin").header("Referer", "test")
                                                   .contentType(MediaType.APPLICATION_JSON)
                                                   .content(objectMapper.writeValueAsString(user)))
                    .andExpect(MockMvcResultMatchers.status().is2xxSuccessful());
    }
Nakul Goyal
  • 593
  • 4
  • 12