[英]Writing JUnit test cases for a Spring Boot Service Application with autowired components
[英]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類?
除了只能在您的應用程序中不創建其他類之外,您還可以創建自己感興趣的類,請參見15.6.1服務器端測試-設置選項
第二個方法是簡單地手動創建控制器實例,而無需加載Spring配置。 相反,會自動創建基本的默認配置(可以大致與MVC JavaConfig或MVC命名空間的配置相媲美),並可在一定程度上進行自定義:
public class MyWebTests {
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.standaloneSetup(new AccountController()).build();
}
// ...
}
您需要為此使用@TestComponent
和@TestConfiguration
,如Spring doc 此處所述
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.