gpt4 book ai didi

java - MockMvc测试: model() and hasItem() methods are undefined

转载 作者:行者123 更新时间:2023-12-01 16:47:40 25 4
gpt4 key购买 nike

我想测试我的 Controller 并使用以下方法来测试它:

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;
}
}

但是编译器无法理解assert部分的model()方法和hasItem()方法,我应该导入哪个包或者哪个.jar文件到这个文件中?

最佳答案

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>

关于java - MockMvc测试: model() and hasItem() methods are undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46944154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com