Spring 引导 - 测试用例 - 不要加载所有组件
Spring Boot - Test Cases - Dont Load All Components
我正试图在 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());
}
}
如何告诉我的测试 类 不要加载我的应用程序的 @Configuration 或 @Component 类?
您需要为此使用 @TestComponent
和 @TestConfiguration
,如 Spring 文档 here
中所述
您可以只创建您感兴趣的 类,而不是不在您的应用程序中创建其他 类,请参阅 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();
}
// ...
}
我正试图在 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());
}
}
如何告诉我的测试 类 不要加载我的应用程序的 @Configuration 或 @Component 类?
您需要为此使用 @TestComponent
和 @TestConfiguration
,如 Spring 文档 here
您可以只创建您感兴趣的 类,而不是不在您的应用程序中创建其他 类,请参阅 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();
}
// ...
}