【问题标题】:Controller layer test in SpringBoot applicationSpring Boot 应用程序中的控制器层测试
【发布时间】:2018-03-25 12:43:28
【问题描述】:

我的 SpringBoot 应用中有一个控制器:

@Controller  
@RequestMapping("/v1/item")  
public class Controller{

@Autowired
private ServiceForController service;

@PostMapping()
public String createItem(@ModelAttribute Item item) {
        Item i = service.createItem(item.getName(), item.getDomain());
        return "item-result";
    }
}

而且我想在 mocks 的帮助下将它与服务分开测试。如何实现它?

【问题讨论】:

    标签: spring-boot mocking spring-test-mvc


    【解决方案1】:

    至少有两种方法可以做到这一点:

    1. 启动整个 SpringBoot 上下文并进行某种集成测试 示例:

      @RunWith(SpringRunner.class)
      @SpringBootTest
      @AutoConfigureMockMvc
      public class ControllerTest {
         @Autowired
         private MockMvc mvc;
      
         @Test
         @WithMockUser(roles = "ADMIN")
         public void createItem() throws Exception {
            mvc.perform(post("/v1/item/")
                  .param("name", "item")
                  .param("domain", "dummy.url.com"))
                  .andExpect(status().isOk());
            //check result logic
      }
      
    2. 测试独占控制器层并将整个加载的上下文仅限于它。示例:

      @RunWith(SpringRunner.class)
      @WebMvcTest(controllers = Controller.class)
      public class ControllerTest{
         @Autowired
         private MockMvc mvc;
      
         @MockBean
         private ServiceForController service;
         //testing methods and their logic
      ...
      }
      

    尽管就使用的资源而言,第二种方法(对我而言)似乎更明智,但由于缺少初始化的 bean,它可能会造成很多不便。例如,在我决定尝试另一种选择之前,我需要创建至少 5 个 bean 的模拟,这些 bean 在我的 ContollerTest 类中的 SpringBoot 启动时添加到上下文中。

    因此,我不得不切换到将@SpringBootTest 与@SpyBean 结合使用的方法,这允许我调用Mockito verify() 方法。

    【讨论】:

      猜你喜欢
      • 2017-10-03
      • 2018-04-27
      • 2019-07-16
      • 1970-01-01
      • 2018-01-02
      • 2020-03-22
      • 2021-08-02
      • 1970-01-01
      • 2021-02-08
      相关资源
      最近更新 更多