简体   繁体   中英

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?

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

    // ...

}

您需要为此使用@TestComponent@TestConfiguration ,如Spring doc 此处所述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM