Ich teste einen Spring-Mvc-Controller, der einen Webservice-Client erhält, der automatisch gestartet wird, und es wurde vai mockito verspottet. Aber das Spotten funktioniert nicht. Aufrufen von "verify (stuClient, mal (1)). GetAllStudents (sAndPCommand);" in Test liefertWebservice-Client kann nicht mit Mockito getaktet werden
Wanted but not invoked:
stuClient.getAllStudents(
[email protected]e50e
);
-> at com.xyz.controllers.StudentControllerTest.testGetHomePage(StudentControllerTest.java:101)
Actually, there were zero interactions with this mock.
at com.xyz.controllers.StudentControllerTest.testGetHomePage(StudentControllerTest.java:101).....
unter meinem Controller-Methode in Test:
@RequestMapping(value = "/getHomePage.do", method = RequestMethod.GET)
public ModelAndView getHomePage(@RequestParam(value = "first", required = false) Integer first,
@RequestParam(value = "max", required = false) Integer max, @RequestParam(value = "sortBy",
required = false) String sortBy,
@RequestParam(value = "sortDirection", required = false) String sortDir) {
ModelAndView mav = new ModelAndView("home");
SortablePagedCommand sortablePagedCommand = new SortablePagedCommand();
sortablePagedCommand.setFirst(first);
sortablePagedCommand.setMax(max);
sortablePagedCommand.setSort(sortBy);
sortablePagedCommand.setSortDir(sortDir);
PagedResult<StudentBean> students = studentServiceClient.getAllStudents(sortablePagedCommand);
List<StudentBean> studentList = students.getItems();
int noOfRecords = students.getUnfilteredItems();
int noOfPages = (int) Math.ceil(noOfRecords * 1.0/max);
mav.addObject("sortByField", sortBy);
mav.addObject("sortDirField", sortDir);
mav.addObject("studentList", studentList);
mav.addObject("noOfPages", noOfPages);
mav.addObject("currentPage", first);
return mav;
}
Und meine Test-Klasse ist unten:
package com.xyz.controllers;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import java.sql.Date;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.xyz.crudserviceclient.beans.StudentBean;
import com.xyz.crudserviceclient.client.StudentServiceClient;
import com.xyz.crudserviceclient.utilitybeans.PagedResult;
import com.xyz.crudserviceclient.utilitybeans.SortablePagedCommand;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "file:WebContent/WEB-INF/dispatcher-servlet.xml" })
@WebAppConfiguration
public class StudentControllerTest {
private MockMvc mockMvc;
@InjectMocks
private StudentController controller;
@Mock
private StudentServiceClient stuClient;
@Autowired
private WebApplicationContext webAppContext;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.webAppContextSetup(webAppContext).build();
Mockito.reset(stuClient);
}
@SuppressWarnings("unchecked")
@Test
public void testGetHomePage() throws Exception {
StudentBean sb1 = new StudentBean();
sb1.setFirstName("Sai");
sb1.setLastName("Palaparthi");
sb1.setGender("Male");
sb1.setDOB(new Date(System.currentTimeMillis()));
sb1.setEmail("[email protected]");
sb1.setMobileNumber("8121157247");
sb1.setAddress("Huda");
sb1.setCourses(Arrays.asList("Math", "Chem"));
StudentBean sb2 = new StudentBean();
sb2.setFirstName("Viswanath");
sb2.setLastName("Palaparthi");
sb2.setGender("Male");
sb2.setDOB(new Date(System.currentTimeMillis()));
sb2.setEmail("[email protected]");
sb2.setMobileNumber("8121157248");
sb2.setAddress("Huda");
sb2.setCourses(Arrays.asList("Math"));
PagedResult<StudentBean> pResult = new PagedResult<StudentBean>(
Arrays.asList(sb1, sb2), 2);
pResult.setFirst(0);
pResult.setUnfilteredItems(2);
Integer first = 0;
Integer max = 5;
String sortBy = "firstname";
String sortDir = "asc";
SortablePagedCommand sAndPCommand = new SortablePagedCommand();
sAndPCommand.setFirst(first);
sAndPCommand.setMax(max);
sAndPCommand.setSort(sortBy);
sAndPCommand.setSortDir(sortDir);
Mockito.when(stuClient.getAllStudents(sAndPCommand))
.thenReturn(pResult);
mockMvc.perform(
get("/getHomePage.do").param("first", String.valueOf(first))
.param("max", String.valueOf(max))
.param("sortBy", sortBy)
.param("sortDirection", sortDir))
.andExpect(status().isOk())
.andExpect(view().name("home"))
.andExpect(forwardedUrl("/jsps/home.jsp"))
.andExpect(model().attribute("sortByField", is(sortBy)))
.andExpect(model().attribute("sortDirField", is(sortDir)))
.andExpect(model().attribute("noOfPages", 1))
.andExpect(model().attribute("currentPage", is(first)))
.andExpect(model().attribute("studentList", hasSize(2)))
.andExpect(
model().attribute(
"studentList",
hasItem(allOf(
hasProperty("firstName", is("Sai")),
hasProperty("lastName",
is("Palaparthi")),
hasProperty("gender", is("Male")),
hasProperty(
"dob",
is(new Date(System
.currentTimeMillis()))),
hasProperty("email",
is("v.p[email protected]")),
hasProperty("mobileNumber",
is("8121157247")),
hasProperty("address", is("Huda")),
hasProperty("courses",
hasItems("Math", "Chem"))))))
.andExpect(
model().attribute(
"studentList",
hasItem(allOf(
hasProperty("firstName",
is("Viswanath")),
hasProperty("lastName",
is("Palaparthi")),
hasProperty("gender", is("Male")),
hasProperty(
"dob",
is(new Date(System
.currentTimeMillis()))),
hasProperty("email",
is("[email protected]")),
hasProperty("mobileNumber",
is("8121157248")),
hasProperty("address", is("Huda")),
hasProperty("courses", hasItems("Math"))))));
verify(stuClient, times(1)).getAllStudents(sAndPCommand);
verifyNoMoreInteractions(stuClient);
}
}
btw das Argument des Aufrufs von 'mockMvc.perform (/*...*/)' ist viel zu komplex. In einem solchen Test sollten Sie sich darauf konzentrieren, dass die korrekte Liste an den Mock übergeben wird (wahrscheinlich mit 'Mockito.same') und nicht den Inhalt der Liste und die Eigenschaften dieser Elemente. – SpaceTrucker
Sie benötigen auch nicht 'Mockito.reset (stuClient);', da ein Mock für jeden Testfall initialisiert wird und ein neu initialisierter Mock per Definition zurückgesetzt wird. – SpaceTrucker