Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot - Test Cases - Dont Load All Components

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?

like image 766
Damien Gallagher Avatar asked Apr 08 '17 09:04

Damien Gallagher


2 Answers

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();
    }

    // ...

}
like image 94
ninj Avatar answered Oct 18 '22 20:10

ninj


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

like image 26
developer Avatar answered Oct 18 '22 20:10

developer