相关疑难解决方法(0)

Spring Boot-控制器测试失败并显示404代码

我想为控制器编写测试。这是测试代码段:

@RunWith(SpringRunner.class)
@WebMvcTest(WeatherStationController.class)
@ContextConfiguration(classes = MockConfig.class)
public class WeatherStationControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private IStationRepository stationRepository;

    @Test
    public void shouldReturnCorrectStation() throws Exception {

        mockMvc.perform(get("/stations")
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk());
    }
}
Run Code Online (Sandbox Code Playgroud)

控制器代码段:

@RestController
@RequestMapping(value = "stations")
public class WeatherStationController {

    @Autowired
    private WeatherStationService weatherService;

    @RequestMapping(method = RequestMethod.GET)
    public List<WeatherStation> getAllWeatherStations() {
        return weatherService.getAllStations();
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public WeatherStation getWeatherStation(@PathVariable String id) {
        return weatherService.getStation(id);
    }
Run Code Online (Sandbox Code Playgroud)

MockConfig类:

@Configuration
@ComponentScan(basePackages = "edu.lelyak.repository")
public class MockConfig {

    //**************************** MOCK BEANS …
Run Code Online (Sandbox Code Playgroud)

spring unit-testing controller spring-boot

4
推荐指数
4
解决办法
1万
查看次数

标签 统计

controller ×1

spring ×1

spring-boot ×1

unit-testing ×1