gpt4 book ai didi

java - Junit - Spring - 测试集合

转载 作者:行者123 更新时间:2023-12-01 18:34:14 27 4
gpt4 key购买 nike

您能否建议谁使用 JUnit 4 和 Spring MVC 测试 Collection?

Controller

@Controller
public class PersonController {
@Autowired
private PersonService personService;

@RequestMapping(value = {"/", "/index"}, method = RequestMethod.GET)
public String getPerson(Model model) {
model.addAttribute("personData", personService.getPerson);
return "personPage";
}
}

测试 Person 类可以通过以下方式完成:

public class TestPersonController {

@Mock
private PersonService personService;

@InjectMocks
private PersonController personController;

private MockMvc mockMvc;

@Before
public void setup() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(personController).build();
}

@Test
public void testGetPerson() throws Exception {
when(personService.getPerson(1L)).thenReturn(new Person(1L, "StackOverflow"));

mockMvc.perform(get("/person/{id}", 1L))
.andExpect(status().isOk())
.andExpect(view().name("personPage"))
.andExpect(model().attribute("personData",
allOf(hasProperty("id", is(1L)),
hasProperty("name", is("StackOverflow")))));
}
}

但是我无法弄清楚如何测试 perService.getPerson 是否返回列表!

最佳答案

@Autowired
private PersonController personController;

private MockHttpServletRequest request;
private MockHttpServletResponse response;
private PersonService personService;

@Before
public void setup() {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
personService = createNiceMock(PersonService.class);
}
@Test
public void shouldCheckRequestMappingForUserDashBoard() throws Exception {
request.setRequestURI("/index");
request.setMethod("GET");
modelAndView = new AnnotationMethodHandlerAdapter().handle(request, response, personController);

// you can call according to what you want to create mock.
expect(personService.getPerson()).andReturn(new Person());
replay(personService);

Assert.assertNotNull(modelAndView.getViewName());
Assert.assertEqual(modelAndView.getViewName(),"personPage");
}

关于java - Junit - Spring - 测试集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22751356/

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