我想为下一个spring MVC控制器编写单元测试用例。
@Controller
@Configuration
@PropertySource("classpath:project/web/properties/RealTimeAPI.properties")
@RequestMapping("/learnon")
public class ClassManagerController {
private final Logger logger = Logger.getLogger(ClassManagerController.class);
@Autowired
private ClassManagerService classManagerService;
@Autowired
private GroupUserService groupUserService;
@RequestMapping(value = "/teacher", method = RequestMethod.GET)
public ModelAndView showClassDetail(HttpServletRequest request, HttpSession httpSession,
@RequestParam(value = "isbn", required = false) String isbn13,
@RequestParam(value = "classId", required = false) Long classId) {
String redirectUrl = "https://example.com/jsp/Login.jsp?reason=failedLogin&redirectUri=https://example.com/secure/Bookshelf";
String accessDeniedUri = "https://example.com/jsp/AccessDenied.jsp";
if (httpSession.getAttribute("USERID") == null) {
return new ModelAndView("redirect:" + redirectUrl);
}
try {
long userId = Long.parseLong(httpSession.getAttribute("USERID").toString());
UserBean user = classManagerService.getUser(userId);
if (httpSession.getAttribute("SCHOOLID") == null) {
httpSession.setAttribute("SCHOOLID", user.getSchoolId());
}
if (httpSession.getAttribute("FULLFILLMENT_YEAR") == null) {
httpSession.setAttribute("FULLFILLMENT_YEAR", user.getFulfillmentYear());
}
String isbn10 = ISBNUtil.convertIsbn13ToIsbn10(isbn13);
String title = "";
ModelAndView mav = null;
ClassManagerBean classBean = null;
if(classId == null && httpSession.getAttribute("classId") != null){
classId = (Long)httpSession.getAttribute("classId");
}
if(classId != null && classId > 0) {
List<UserBean> userBeanList = classManagerService.getUserList(user.getSchoolId(), classId, isbn10);
classBean = classManagerService.getClassById(classId);
classBean.setUserNumber(userBeanList.size());
title = classBean.getTitle();
//Set the view to ClassManager.jsp
mav = new ModelAndView("ClassManager");
mav.addObject("userList", userBeanList);
boolean authorized = userBeanList.stream().anyMatch(u->u.getUserId() == userId);
if(!authorized){
ModelAndView modelAndView = new ModelAndView("redirect:" + accessDeniedUri);
modelAndView.addObject("accessDenied", "true");
return modelAndView;
}
}else{
title = classManagerService.getTitle(isbn10);
//Set the view to createNewClass.jsp
mav = new ModelAndView("CreateNewClass");
classBean = new ClassManagerBean();
classBean.setLo2Flag(true);
classBean.setIsbn(isbn10);
classBean.setTitle(title);
}
httpSession.setAttribute("searchTitle", title);
httpSession.setAttribute("selectedIsbn", isbn10);
httpSession.setAttribute("classId", classId);
mav.addObject("user", user);
mav.addObject("classBean", classBean);
return mav;
} catch (Exception ex) {
ModelAndView mav2 = new ModelAndView("redirect:" + accessDeniedUri);
mav2.addObject("accessDenied", "true");
logger.error("Exception Occurred, Redirecting to Access Denied...", ex);
return mav2;
}
}
}
我已经为上述类编写了以下单元测试用例。
@RunWith(PowerMockRunner.class)公共类ClassManagerController测试{
public ClassManagerService classManagerService;
public GroupUserService groupUserService;
private MockMvc mockMvc;
@InjectMocks
private ClassManagerController classManagerController;
@Before
public void setUp() {
classManagerService = Mockito.mock(ClassManagerService.class);
groupUserService = Mockito.mock(GroupUserService.class);
mockMvc = MockMvcBuilders.standaloneSetup(classManagerController).build();
}
@Test
public void testShowClassDetail() throws Exception {
HttpServletRequest httpRequest = mock(HttpServletRequest.class);
HttpSession httpSession = mock(HttpSession.class);
Mockito.when(httpSession.getAttribute("USERID")).thenReturn(null);
RequestBuilder request = MockMvcRequestBuilders
.get("/learnon/teacher")
.param("isbn", "1234567890123")
.param("classId", "1")
.accept(MediaType.APPLICATION_JSON);
String modalView = "redirect:" + "https://example.com/jsp/Login.jsp?reason=failedLogin&redirectUri=https://www.example.com/secure/Bookshelf";
ResultActions result = mockMvc.perform(request)
.andExpect(status().is3xxRedirection())
.andExpect(view().name(modalView));
}
@Test
public void testShowClassDetail1() throws Exception {
HttpServletRequest httpRequest = mock(HttpServletRequest.class);
HttpSession httpSession = mock(HttpSession.class);
Mockito.when(httpSession.getAttribute("USERID")).thenReturn(Mockito.anyString());
//Line 87
List<UserBean> spyList = Mockito.mock(List.class);
Mockito.when(classManagerService.getUserList(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyString())).thenReturn(spyList);
Mockito.when(spyList.stream().anyMatch(u->u.getUserId() == Mockito.anyLong())).thenReturn(true);
RequestBuilder request = MockMvcRequestBuilders
.get("/learnon/teacher")
.param("isbn", "1234567890123")
.param("classId", "1")
.accept(MediaType.APPLICATION_JSON);
String modalView = "redirect:" + "https://example.com/jsp/AccessDenied.jsp";
ResultActions result = mockMvc.perform(request)
.andExpect(status().is3xxRedirection())
.andExpect(view().name(modalView));
}
第一个单元测试用例成功通过。
第二次测试失败,出现以下错误。
组织。莫基托。例外情况。滥用。InvalidUseOfMatcherException:此处检测到放错位置的参数匹配器:
-
您不能在验证或存根之外使用参数匹配器。参数匹配器的正确用法示例:时(mock.get(anyInt())). then返回(null); doThrow(new RuntimeExc0019()).时(mock).某位Voidmethod(anyObject());验证(mock).某位方法(包含(foo))
此外,此错误可能会出现,因为您将参数匹配器与无法模拟的方法一起使用。以下方法无法存根/验证:final/private/equals()/hashCode()。不支持对非公共父类声明的模拟方法。
至少,我是经理。Spring网状物控制器。ClassManagerController测试。sun上的testShowClassDetail1(ClassManagerControllerTest.java:90)。反映NativeMethodAccessorImpl。在sun上调用0(本机方法)。反映NativeMethodAccessorImpl。在sun上调用(NativeMethodAccessorImpl.java:62)。反映DelegatingMethodAccessorImpl。调用(DelegatingMethodAccessorImpl.java:43)
问题在于代码:
Mockito.when(httpSession.getAttribute("USERID")).thenReturn(Mockito.anyString());
httpSession。当您返回字符串时,getAttribute(“USERID”)实际上返回“Object”。
如果你尝试,
Mockito.when(httpSession.getAttribute("USERID")).thenReturn(new String("anyString"));,
然后我就可以工作了。
希望它对你有用。
我试图模拟EntityPersistor的一个方法 我想检查queryString是否匹配特定的queryString,以及params是否包含特定的值。如果那两个条件为真,我想返回一个特定的对象XY。 在此处检测到错误的参数匹配器: 我该怎么解决呢?或者是否有更好的方法来模拟一个方法并定义一个特定的返回大小写(如果param1 eq x和param2 eq y)?
使用Mockito,我想一个参数列表中包含的方法调用,但我没有找到如何编写这一点。 我只想要类似于的东西,如何使用Mockito实现这一点?
在setUp()方法下一行中: 以下是错误: org.mockito.exceptions.misusing.invaliduseofmatchersexception:在此处检测到错误放置或错误使用的参数匹配器: ->在com.auditService.test.auditServiceClientTest.setup(auditServiceClientTest.java:72) when(m
在BundleProcessorTest.java中的以下两个测试用例中,我的第一个测试用例成功地通过了异常。 org.mockito.exceptions.misusing.invaliduseofmatchersexception:在此处检测到错误的参数匹配器: ->在bundle.test.bundleProcessorTest.bundlePluginShouldNotBenull(Bun
问题内容: 在 BundleProcessorTest.java 的以下两个测试用例中,尽管我的第一个测试用例成功通过,但我低于异常。 org.mockito.exceptions.misusing.InvalidUseOfMatchersException:在此处检测到放错位置的参数匹配器: ->在bundle.test.BundleProcessorTest.bundlePluginShoul