MockMvc测试:model()和hasItem()方法未定义

时间:2017-10-26 00:51:48

标签: java spring junit spring-test

我想测试我的控制器并使用以下测试它:

package spittr.web;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.servlet.view.InternalResourceView;

import spittr.data.Spittle;
import spittr.data.SpittleRepository;

public class SpittleControllerTest {
    @Test
    public void shouldShowRecentSpittles() throws Exception {
        List<Spittle> expectedSpittles = createSpittleList(20);
        SpittleRepository mockRepository = Mockito.mock(SpittleRepository.class);

        Mockito.when(mockRepository.findSpittles(Long.MAX_VALUE, 20))
            .thenReturn(expectedSpittles);

        SpittleController controller = new SpittleController(mockRepository);

        MockMvc mockMvc = standaloneSetup(controller)
            .setSingleView(
                new InternalResourceView("/WEB-INF/views/spittles.jsp"))
            .build();

        mockMvc.perform(get("/spittles"))
            .andExpect(view().name("spittles"))
            .andExpect(model().attributeExists("spittleList"))
            .andExpect(model().attribute("spittleList", hasItems(expectedSpittles.toArray())));
    }

    private List<Spittle> createSpittleList(int count) {
        List<Spittle> spittles = new ArrayList<Spittle>();

        for (int i=0; i < count; i++) {
            spittles.add(new Spittle("Spittle " + i, new Date()));
        }

        return spittles;
    }
}

但编译器无法理解断言部分中的 model()方法和 hasItem()方法,我应该将哪个包或.jar文件导入此文件?

1 个答案:

答案 0 :(得分:4)

model()org.springframework.test.web.servlet.result.MockMvcResultMatchers

上的静态方法

view()也是org.springframework.test.web.servlet.result.MockMvcResultMatchers

上的静态方法

org.springframework.test.web.servlet.result.MockMvcResultMatchersorg.springframework:spring-test提供。

我怀疑你的类路径上有这个,否则对MockMvc的引用都不会编译。

我认为您遇到的问题是hasItems(),这来自org.hamcrest.Matchers。此依赖关系的Maven坐标为:

<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-library</artifactId>
    <version>1.3</version>
    <scope>test</scope>
</dependency>