Java Spring5.0.7.0版本中的Web层单元测试和集成测试
我有一个SpringBoot应用程序。使用此测试,但它不会注入和模拟类Java Spring5.0.7.0版本中的Web层单元测试和集成测试,java,spring,spring-mvc,mocking,mockito,Java,Spring,Spring Mvc,Mocking,Mockito,我有一个SpringBoot应用程序。使用此测试,但它不会注入和模拟类 @RunWith(SpringRunner.class) @WebAppConfiguration @ContextConfiguration(locations = { "classpath:testDatabaseContext.xml", "classpath:testServicesContext.xml", "clas
@RunWith(SpringRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {
"classpath:testDatabaseContext.xml",
"classpath:testServicesContext.xml",
"classpath:servlet.xml"
})
public class TerritoriClandestiControllerTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Mock
TerritoriClandestiRepository territoriClandestiRepository = mock(TerritoriClandestiRepository.class);
@InjectMocks
private TerritoriClandestiService territoriClandestiService;
List<Object[]> list;
Resource listResource = new ClassPathResource("list.txt");
@Before
public void setup() throws IOException {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)
.build();
list = DataLoader.readLines(listgetInputStream());
}
@Test
public void getAll() throws Exception {
when(territoriClandestiRepository.findAllBaseData(anyLong())).thenReturn(list);
mockMvc.perform(get("/terrcland")
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andDo(print())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(status().isOk())
.andExpect(jsonPath("$.*", hasSize(1)));
}
}
@RunWith(SpringRunner.class)
@WebAppConfiguration
@上下文配置(位置={
“classpath:testDatabaseContext.xml”,
“classpath:testServicesContext.xml”,
“类路径:servlet.xml”
})
公共类领土秘密控制员测试{
@自动连线
私有WebApplicationContext wac;
私有MockMvc-MockMvc;
@嘲弄
TerrititorSeconditRepository TerrititorSeconditRepository=mock(territitorSeconditRepository.class);
@注射模拟
私人领地秘密服务领地秘密服务;
名单;
Resource listResource=new ClassPathResource(“list.txt”);
@以前
public void setup()引发IOException{
this.mockMvc=MockMvcBuilders.webAppContextSetup(this.wac)
.build();
list=DataLoader.readLines(listgetInputStream());
}
@试验
public void getAll()引发异常{
when(territorisecretidesrepository.findAllBaseData(anyLong())。然后return(list);
mockMvc.perform(get(“/terrcland”)
.contentType(MediaType.APPLICATION\u JSON\u UTF8\u值))
.andDo(print())
.andExpect(content().contentType(MediaType.APPLICATION\u JSON\u UTF8\u VALUE))
.andExpect(状态().isOk())
.andExpect(jsonPath($*),hasSize(1));
}
}
您可以使用@MockBean
而不是@Mock
,它将在spring上下文中将字段导出为bean
公共类地域秘密控制器测试{
@蚕豆
私人领地秘密存储库领地秘密存储库;
}
或者你也可以这样做
@RunWith(SpringRunner.class)
@WebAppConfiguration
@上下文配置(位置={
“classpath:testDatabaseContext.xml”,
“classpath:testServicesContext.xml”,
“类路径:servlet.xml”
},classes={territorisecretdesticcontrollertest.Config.class})
公共类领土秘密控制员测试{
@测试配置
静态类配置{
@豆子
Territory秘密存储库Territory秘密存储库(){
返回Mockito.mock(territorisecretdestinepository.class);
}
}
@自动连线
私人领地秘密存储库领地秘密存储库;
}