【问题标题】:How to mock autowired dependencies in Spring Boot MockMvc Unit tests?如何在 Spring Boot MockMvc 单元测试中模拟自动装配的依赖项?
【发布时间】:2016-09-23 23:43:43
【问题描述】:

我正在扩展基本的 Spring Boot 示例,向我的控制器添加“自动装配”存储库依赖项。我想修改单元测试来为该依赖注入一个 Mockito 模拟,但我不确定如何。

我期待我可以做这样的事情:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MockServletContext.class)
@WebAppConfiguration
public class ExampleControllerTest {

    private MockMvc mvc;

    @InjectMocks
    ExampleController exampleController;

    @Mock
    ExampleRepository mockExampleRepository;

    @Before
    public void setUp() throws Exception {
      MockitoAnnotations.initMocks(this);
    mvc = MockMvcBuilders.standaloneSetup(new ExampleController()).build();
    }

    @Test
    public void getExamples_initially_shouldReturnEmptyList() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/example").accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().string(equalTo("[]")));
    }
}

但它不会将模拟注入MockMvc。谁能解释如何使用 @Autowired 依赖项而不是构造函数参数来做到这一点?

【问题讨论】:

  • 创建一个包含 bean 模拟的配置。然后在您的设置中重置模拟。 (在 Spring Boot 1.4 中,您将能够添加 @MockBean 注释,这使得这更容易)。

标签: spring-boot mockito


【解决方案1】:

请使用@RunWith(MockitoJUnitRunner.class) 而不是@RunWith(SpringJUnit4ClassRunner.class) 并且您必须将ExampleController exampleController; 字段与注入的模拟一起使用,而不是在mvc = MockMvcBuilders.standaloneSetup(new ExampleController()).build(); 中创建一个新的模拟

【讨论】:

  • 这很有趣。我没听说过那门课。但是,这一更改似乎不会导致模拟依赖项被自动装配
  • 请尝试使用@RunWith(Mockito...) 并在这一行中使用mvc = MockMvcBuilders.standaloneSetup(new ExampleController()).build(); 注入模拟的exampleController。如果您像在此行中那样创建示例控制器的新实例,则不会应用自动连接。
  • 不错。这似乎是诀窍。如果您有机会,请更新您的答案以包含此附加信息。另外,感谢您为我节省了大量时间。
  • 答案已更改,祝您有美好的一天。
  • 其中哪一个?来自org.mockito.junit 的那个还是来自`org.mockito.runners 的那个?
猜你喜欢
  • 1970-01-01
  • 2018-03-28
  • 2021-10-19
  • 2016-03-29
  • 2020-12-02
  • 2012-07-11
  • 2021-12-03
  • 1970-01-01
  • 2023-03-13
相关资源
最近更新 更多