Saya ingin menulis kasus uji unit untuk pengontrol MVC pegas berikut.

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

}

Saya telah menulis kasus uji unit berikut untuk kelas di atas.

@RunWith(PowerMockRunner.class) kelas publik ClassManagerControllerTest {

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

   }

Kasus uji unit pertama berhasil dilewati.

Tes kedua gagal dengan kesalahan berikut.

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Pencocokan argumen yang salah tempat terdeteksi di sini:

-> di learnonclassmanager.spring.web.controller.ClassManagerControllerTest.testShowClassDetail1(ClassManagerControllerTest.java:87)

Anda tidak dapat menggunakan pencocokan argumen di luar verifikasi atau penghentian. Contoh penggunaan pencocokan argumen yang benar: when(mock.get(anyInt())).thenReturn(null); doThrow(New RuntimeException()).kapan(mock).someVoidMethod(anyObject()); verifikasi(tiruan).someMethod(berisi("foo"))

Juga, kesalahan ini mungkin muncul karena Anda menggunakan pencocokan argumen dengan metode yang tidak bisa diremehkan. Metode berikut tidak bisa menjadi dimatikan/diverifikasi: final/pribadi/sama dengan()/kode hash(). Metode mengejek dideklarasikan pada kelas induk non-publik tidak didukung.

di learnonclassmanager.spring.web.controller.ClassManagerControllerTest.testShowClassDetail1(ClassManagerControllerTest.java:90) di sun.reflect.NativeMethodAccessorImpl.invoke0(Metode Asli) di sun.reflect.NativeMethodAccessor(NativeMethodAccessorImpl.invod) .DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

1
Niranga Sandaruwan 20 Mei 2020, 16:21

1 menjawab

Jawaban Terbaik

Masalahnya adalah dengan kode:

Mockito.when(httpSession.getAttribute("USERID")).thenReturn(Mockito.anyString());

HttpSession.getAttribute("USERID") sebenarnya mengembalikan "Objek", saat Anda mengembalikan sebuah String.

Jika kamu mencoba,

Mockito.when(httpSession.getAttribute("USERID")).thenReturn(new String("anyString"));,

Maka saya bekerja dengan baik.

Berharap jika itu berhasil untuk Anda.

1
Lazycoder_007 20 Mei 2020, 13:51