voipp
voipp

Reputation: 1469

How to create and use controllers specifically for test?

I want to have my Spring test with context that contains a controller. This controller is not visible outside the tests and serves only purpose of testing. So when i perform request through mockMvc, this request reach a controller.

How should i define the controller? I don't want to place it outside test package, because i don't need it there.

Upvotes: 1

Views: 1921

Answers (1)

Anatoliy Korovin
Anatoliy Korovin

Reputation: 436

You can mark your controller by the test profile and this bean doesn't instantiate in the production mode:

@Profile("test")
@RestController
@RequestMapping("/apiUrl")
public class TestController {
  ...
}

Also, if you use spring boot you can use the TestConfiguration immediately in your tests:

@SpringBootTest
@ExtendsWith(SpringExtension.class)
public class ApiTest {

    @Test
    void testApi() {
        // send request to test API
    }

    @TestConfiguration
    public static class TestConfig {        

        @RestController
        @RequestMapping("/apiUrl")
        public class TestController {

            @GetMapping("/test")
            public String test() {
                return "STUB";
            }
        }
    }
}

Upvotes: 4

Related Questions