如何在 Junit WebMvcTest 的 RestController 中访问文件(或其 getter 和 setter)?

问题描述 投票:0回答:1

目前我正在使用 Junit 和 Mockito 为 spring boot 应用程序编写单元测试。我最近遇到的问题是我们有一个 RestController 类,它有一些字段。

一些字段被注入到构造函数中,可以被模拟。

但是我有一个私有字段,它不是使用构造函数初始化的,只能使用 setter 方法初始化。

让我们看一下代码:

@RequestMapping("/api/directory")
public class DirectoryController {
     private final DirectoryService service;
     private ScheduledFuture future;

     public ScheduledFuture getFuture() {
        return future;
    }

    public void setFuture(ScheduledFuture future) {
        this.future = future;
    }

    public DirectoryController (DirectoryService service) {
        this.service = service;
    }


    @GetMapping(value = "/sync")
    public String sync(){
       if(getFuture() == null) throw new RuntimeException();

       // do some work

    }
  
}

这里“ScheduledFuture future”应该使用它的setter方法初始化。 现在,我无法在此类(我们使用 future 字段)中为 sync() 编写适当的 WebMvcTest。因为 future 是空的,除非我以某种方式初始化它,否则该方法将抛出异常。

但我不知道该怎么做。

任何帮助将不胜感激。

spring-boot junit mockito spring-test spring-test-mvc
1个回答
0
投票

没有什么能阻止你手动调用设置器。

假设您有如下测试:

@WebMvcTest(DirectoryController.class)
class YourTest{
    @Autowired
    private MockMvc mockMvc;
    @Test
    void testSync() throws Exception{
        mockMvc
            .perform(get("/api/directory/sync"))
            .andExpect(status().isOK());
        //some other checks
    }

}

您可以只自动装配控制器,创建您的模拟对象,然后在发出请求之前调用设置器:

@WebMvcTest(DirectoryController.class)
class YourTest{
    @Autowired
    private MockMvc mockMvc;
    @Autowired
    private DirectoryController directoryController;//controller is autowired
    @Test
    void testSync() throws Exception{
        ScheduledFuture future = createYourMockObject();
        directoryController.setFuture(future);//HERE
        mockMvc
            .perform(get("/api/directory/sync"))
            .andExpect(status().isOK());
        //some other checks
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.