web层单元测试和集成测试

cunj1qz1  于 2021-07-07  发布在  Java
关注(0)|答案(1)|浏览(236)

我有一个springboot应用程序。但它不会注入和模拟类

@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)));
    }
}
oknwwptz

oknwwptz1#

你可以用 @MockBean 而不是 @Mock ,它将字段导出为spring上下文中的bean。

public class TerritoriClandestiControllerTest  {
   @MockBean
   private TerritoriClandestiRepository territoriClandestiRepository;
}

或者你也可以这样做

@RunWith(SpringRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {
        "classpath:testDatabaseContext.xml",
        "classpath:testServicesContext.xml",
        "classpath:servlet.xml"
}, classes = {TerritoriClandestiControllerTest.Config.class})
public class TerritoriClandestiControllerTest  {

   @TestConfiguration
   static class Config {
      @Bean
      TerritoriClandestiRepository territoriClandestiRepository() {
         return Mockito.mock(TerritoriClandestiRepository.class);
      }
   }

   @Autowired
   private TerritoriClandestiRepository territoriClandestiRepository;
}

相关问题