有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JavaSpring启动测试用例不会加载所有组件

我试图在春季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());
    }
}

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


共 (2) 个答案

  1. # 1 楼答案

    您可以只创建感兴趣的类,而不是不在应用程序中创建其他类,请参见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();
        }
    
        // ...
    
    }
    
  2. # 2 楼答案

    您需要使用@TestComponent@TestConfiguration,如Spring文档here中所述