java - 无法使用 DAO 模拟编写集成测试 Controller ?

标签 java spring-boot spring-test spring-restcontroller springmockito

我变得疯狂,我尝试了各种测试运行程序和可能的注释的所有可能组合进行测试,我需要的最接近的解决方案如下:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {MyApplication.class})
@WebAppConfiguration
public class MyControllerTest {

    MockMvc mockMvc;

    // My DAO is an interface extending JpaRepository
    @Mock
    MyDAO myDAO;

    @Autowired
    WebApplicationContext webApplicationContext;

    @Before
    public void setUp() throws Exception {
        List<MyItem> myItems = new ArrayList(){{
            // Items init ...
        }}
        Mockito.when(myDAO.findAll()).thenReturn(myItems);
        /* Other solution I tried with different annotations: 
        * given(myDAO.findAll()).willReturn(myItems);
        * this.mockMvc = MockMvcBuilders.standaloneSetup(myController).build();
        */
        this.mockMvc = webAppContextSetup(webApplicationContext).build();

    }

    @After
    public void tearDown() throws Exception {
//        Mockito.reset(myDAO);
    }

    @Test
    public void getItems() {
        String res = mockMvc.perform(get("/items"))/*.andExpect(status().isOk())*/.andReturn().getResponse().getContentAsString();
        assertThat(res, is("TODO : string representation of myItems ..."));
        assertNull(res); // For checking change in test functionning
    }
}

我很好地在 Controller 方法和服务方法中进入 Debug模式,但是当我看到 DAO 类型时,它不是 Mock,并且 findAll() 总是返回空 ArrayList(),即使我这样做:

Mockito.when(myDAO.findAll()).thenReturn(myItems);

我没有提出异常,我的 DAO 没有被 mock ,尽管我找到了所有的教程,但我不知道该怎么做。 我发现的最接近我需要的教程是这个 Unit Test Controllers with Spring MVC Test但还不够,因为他想要模拟服务注入(inject) Controller 以测试 Controller ,我想模拟 DAO 注入(inject)到注入(inject) Controller 的真实服务中(我想测试 Controller +服务)。

在我看来,我已经通过在测试类上使用注释来做到了这一点,该注释指定了在测试模式下 Spring 应用程序必须实例化哪些类以及必须模拟哪些类,但我不记得'-_ -.

需要你的帮助,这让我发疯!

非常感谢!

最佳答案

对于 @Mock 注释,您需要额外的初始化:

    @Before
    public void initMocks() {
        MockitoAnnotations.initMocks(this);
    }

或者将 runner 更改为 @RunWith(MockitoJUnitRunner... ,但不确定这种情况下的 spring 上下文初始化。

关于java - 无法使用 DAO 模拟编写集成测试 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49046667/

相关文章:

java - 如何使用相同的库在 Eclipse 中编译和运行?

java - Spring-boot登录成功后如何限制POST Rest Api公开访问

java - 获取 MockMvc perform() 方法的错误

java - 使用 Maven 动物嗅探器插件检查自己的 API

java - Java 中的泛型方法 : "Object does not take parameters"

java - 如何将 Spring Cloud Stream Function Bean 连接到 Kafka Binder?

java - 当应用程序没有生产者时,如何让 Spring Cloud Stream 创建 RabbitMQ 队列并绑定(bind)?

spring - 在集成测试中使用 Spring @ActiveProfile

spring - @MockBeans 示例使用

java - 如何将我的 Java Selenium 测试拆分为单独的类?