8

I am trying to to rest my rest classes in Spring MVC

If I run the following code (ran fine when the project was small but now fails) it tries to load all the different components in my application. This includes beans which interact with external systems and need credentials in order to connect

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class TestDummyRest extends BaseRestTestCase{

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private IDummyServices mockDummyServices;


    @Test
    public void getSendGoodMessage() throws Exception {

        given(mockDummyServices.sendGoodMessage(Mockito.anyString())).willReturn(true);

        mockMvc.perform(get("/dummy"))
                    .andExpect(status().isOk())
                    .andExpect(content().contentType(TEXT_PLAIN_CONTENT_TYPE));

        verify(mockDummyServices, times(1)).sendGoodMessage(Mockito.anyString());
    }
}

How do I tell my test classes not to load the @Configuration or @Component classes of my application?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Damien Gallagher
  • 535
  • 1
  • 6
  • 16

2 Answers2

6

Instead of not creating other classes in your application, you could only create the classes you are interested in, see 15.6.1 Server-Side Tests - Setup Options

The second is to simply create a controller instance manually without loading Spring configuration. Instead basic default configuration, roughly comparable to that of the MVC JavaConfig or the MVC namespace, is automatically created and can be customized to a degree:

public class MyWebTests {

    private MockMvc mockMvc;

    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.standaloneSetup(new AccountController()).build();
    }

    // ...

}
ninj
  • 1,529
  • 10
  • 10
1

You need to use @TestComponent and @TestConfiguration for this as explained in Spring doc here

Vasu
  • 21,832
  • 11
  • 51
  • 67
  • 1
    Tried those with no joy - the documentation suggests its to prevent your application loading test configuration. If your application uses component scanning, for example if you use @ SpringBootApplication or @ ComponentScan, you may find components or configurations created only for specific tests accidentally get picked up everywhere. To help prevent this, Spring Boot provides @ TestComponent and @ TestConfiguration annotations that can be used on classes in src/test/java to indicate that they should not be picked up by scanning. – Damien Gallagher Apr 08 '17 at 09:31