Spring Boot - 控制器测试失败,404 代码 [英] Spring Boot - Test for controller fails with 404 code

查看:26
本文介绍了Spring Boot - 控制器测试失败,404 代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为控制器编写一个测试.这是测试片段:

I want to write a test for controller. Here is test snippet:

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

控制器代码片段:

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

MockConfig 类:

MockConfig class:

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

    //**************************** MOCK BEANS ******************************

    @Bean
    @Primary
    public WeatherStationService weatherServiceMock() {
        WeatherStationService mock = Mockito.mock(WeatherStationService.class);
        return mock;
    }

这是错误堆栈跟踪:

java.lang.AssertionError: Status 
Expected :200
Actual   :404

我知道这里出了什么问题.
如何修复控制器测试?

I can get what is wrong here.
How to fix test for controller?

推荐答案

HTTP 代码 404,意味着没有为您的请求找到(在服务器上)资源,我认为您的控制器在 spring 启动时不可见(让我说未扫描).

HTTP code 404, means no resource found (on the server) for your request, which I think that your controller is not visible(let me say is not scanned) by spring boot.

一个简单的解决方案是扫描MockConfig类中的父包,这样spring就可以拾取所有bean,

A simple solution is scanning a parent package in MockConfig class, so spring can pick up all beans,

@ComponentScan(basePackages = "edu.lelyak") // assuming that's the parent package in your project

如果你不喜欢这种方式,可以在basePackages

if you don't like this approach, you can add the controller's package name in basePackages

@ComponentScan(basePackages = {"edu.lelyak.controller","edu.lelyak.repository") 

顺便说一句,您不必在MockConfig 类中手动设置WeatherStationService,Spring boot 可以为您注入一个模拟并在每个测试方法后自动重置它,你应该在你的测试类中声明它:

BTW, you don't have to manually set up WeatherStationService in MockConfig class, Spring boot can inject a mock for you and automatically reset it after each test method, you should just declare it in your test class:

@MockBean
private IStationRepository stationRepository;

另一方面,您应该在测试方法中调用 get("/stations") 之前模拟 weatherService.getAllStations()(因为您没有运行集成测试),所以你可以这样做:

On the other hand, you should mock weatherService.getAllStations() before calling get("/stations") in your test method (as you're not running integration test), so you can do:

List<WeatherStation> myList = ...;
//Add element(s) to your list
 Mockito.when(stationService.getAllStations()).thenReturn(myList);

您可以在以下位置找到更多信息:

You can find more in :

Spring Boot 特性: 测试

这篇关于Spring Boot - 控制器测试失败,404 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆