Spring Boot-测试用例-不加载所有组件

Dam*_*her 5 java spring spring-test spring-boot

我试图在Spring MVC中休息我的休息课

如果我运行以下代码(当项目很小但现在失败时可以运行),它将尝试加载应用程序中的所有不同组件。这包括与外部系统交互并需要凭据才能连接的bean

@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());
    }
}
Run Code Online (Sandbox Code Playgroud)

如何告诉测试类不要加载应用程序的@Configuration或@Component类?

nin*_*inj 5

您可以只创建您感兴趣的类,而不是不在您的应用程序中创建其他类,请参阅15.6.1 服务器端测试 - 设置选项

第二种是简单的手动创建控制器实例,不加载Spring配置。取而代之的是基本的默认配置,大致类似于 MVC JavaConfig 或 MVC 命名空间的配置,是自动创建的,并且可以在一定程度上进行自定义:

public class MyWebTests {

    private MockMvc mockMvc;

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

    // ...

}
Run Code Online (Sandbox Code Playgroud)