vendredi 1 avril 2016

Spring MVC controller testing using junit and mockito - Circular view path Exception is thrown

How to overcome circular path without chaning the uri and the string thats being returned, can I make it working only with some help of mockito or somethings else without touching my actual controller. In my manager controller I have a get and post methods with the same uri and I am using titles view resolver in actual fly of application to map the respective views. However, when I wanted to test my controller and I am using junit and mockito, it threw me an Circular-path exception. And i am also aware that this exception is thrown because I have to methods with the same uri to that of the same return string and now how do i tell the junit that to check the titles view resolver to find the appropriate views or how do i tell the the return type string is for the post to get mapped or atleast how to tell to ignore the return type string value.

THIS IS MY MANAGER CONTROLLER WITH GET AND POST ----- 
GET-

@RequestMapping(value = "newemployee", method = RequestMethod.GET)
    public ModelAndView newEmployeeGet(HttpServletRequest request) {
        UserDetails userDetails = getUserDetails();
        GradeMasterLookUp grade = gradeLookUpDao.getGradeOfLoginUser(userDetails);
        Map map = new HashMap();
        map.put("csroles", getUserCSRoles());
        if (userDetails != null)
            map.put("username", userDetails.getUsername().toString());
        map.put("newemployee", new EmployeeDetails());

        map.put("stateList", lookUpSer.getStateLookUps());
        // map.put("grade", loginUsersSer.getAllGradeByLoginUser(userDetails));
        map.put("grade", loginUsersDao.getAllGradeNameByLoginUserForDataEntry(userDetails));

        map.put("cityList", lookUpSer.getCityLookUps());
        map.put("designations", lookUpSer.getDesignationLookUps());
        map.put("departments", lookUpSer.getDepartmentLookUps());
        map.put("photoIdList", photoIdMasterDao.getPhotoIdMasterList());
        map.put("subdepartments", lookUpSer.getSubDepartmentLookUps());
        map.put("recuritmentSrcList", recruitmentSourceMasterDao.getRecruitmentSourceMasterList());
        List<RegionDetail> regionDetails=regionDetailDao.getRegionDetailList();
        map.put("regions", regionDetails);
        map.put("branchcodes", lookUpSer.getAllErcRlgMaster1());
        map.put("locations", lookUpSer.getLocationLookuUps());
        map.put("documentList", fileUploadDetailsDao.getDocumentTypeListGreaterThanId(100));
        String ss = "[\"1-1-2016\",\"2-1-2016\",\"3-1-2016\",\"4-1-2016\",\"5-1-2016\",\"6-1-2016\",\"7-1-2016\",\"8-1-2016\"]";
        map.put("holidays", ss.toString());
        return new ModelAndView(prefixResult + "newemployee", map);
    }

POST -

@RequestMapping(value = "newemployee", method = RequestMethod.POST)
    public ModelAndView newEmployeePost(@ModelAttribute("newemployee") EmployeeDetails details,
            HttpServletRequest request) {

        UserDetails userDetails = getUserDetails();
        if (details.getId() == null) {
            details.setQueueType(managerService.getQueueTypeByCode(QueueType.L1_DATA_ENTRY, userDetails));
            details.setPanCardNo(details.getPanCardNo().toUpperCase());
            return new ModelAndView(
                    new RedirectView("upload?empId=" + managerService.saveEmployee(details, userDetails)));
        } else {
            details.setQueueType(managerService.getQueueTypeByEmpId(details.getId(), userDetails));
            details.setPanCardNo(details.getPanCardNo().toUpperCase());
            managerService.saveEmployee(details, userDetails);
            if (details.getQueueType().getCode().equalsIgnoreCase(QueueType.L1_DATA_ENTRY)) {
                return new ModelAndView(
                        new RedirectView("upload?empId=" + managerService.saveEmployee(details, userDetails)));
            } else {
                return new ModelAndView(
                        new RedirectView("upload?empId=" + managerService.saveEmployee(details, userDetails)));
            }
        }
    }

MY MANAGER TEST CLASS IS -

/**
 * 
 */
package com.rectrix.ool.test.controller;

import static org.hamcrest.Matchers.instanceOf;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
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.request.MockMvcRequestBuilders.get;

import java.util.Arrays;
import java.util.List;

import junit.framework.TestCase;

import org.apache.tiles.TilesApplicationContext;
import org.apache.tiles.startup.TilesInitializer;
import org.hamcrest.generator.HamcrestFactoryWriter;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.ContextHierarchy;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
import org.springframework.web.servlet.view.tiles2.TilesConfigurer;
import org.springframework.web.servlet.view.tiles2.TilesView;

import com.ing.INGcrypter.ECDCtool;
import com.ing.INGcrypter.NeeDcrypt;
import com.rectrix.ool.controller.ManagerController;
import com.rectrix.ool.dao.FileUploadDetailsDao;
import com.rectrix.ool.dao.LoginUsersDao;
import com.rectrix.ool.dao.PhotoIdMasterDao;
import com.rectrix.ool.dao.RecruitmentSourceMasterDao;
import com.rectrix.ool.lookup.dao.GradeLookUpDao;
import com.rectrix.ool.lookup.dao.RegionDetailDao;
import com.rectrix.ool.lookup.models.CityLookUp;
import com.rectrix.ool.lookup.models.DepartmentLookUp;
import com.rectrix.ool.lookup.models.DesignationLookUp;
import com.rectrix.ool.lookup.models.ErcRlgMaster1;
import com.rectrix.ool.lookup.models.GradeMasterLookUp;
import com.rectrix.ool.lookup.models.LocationLookuUp;
import com.rectrix.ool.lookup.models.RegionDetail;
import com.rectrix.ool.lookup.models.StateLookUp;
import com.rectrix.ool.lookup.models.SubDepartmentLookUp;
import com.rectrix.ool.models.DocumentType;
import com.rectrix.ool.models.EmployeeDetails;
import com.rectrix.ool.models.PhotoIdMaster;
import com.rectrix.ool.models.RecruitmentSourceMaster;
import com.rectrix.ool.service.FileUploadDetailsSer;
import com.rectrix.ool.service.LoginUsersSer;
import com.rectrix.ool.service.LookUpSer;
import com.rectrix.ool.service.ManagerService;
import com.rectrix.ool.utils.impl.FileWriter;

/**
 * @author rectrix
 *
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextHierarchy({
@ContextConfiguration(loader=AnnotationConfigContextLoader.class)   
})
public class TestManagerController extends TestCase{

    @Autowired
    private LookUpSer lookUpSer;

    @Autowired
    private LoginUsersSer loginUsersSer;

    @Autowired
    private LoginUsersDao loginUsersDao;

    @Autowired
    private ManagerService managerService;

    @Autowired
    private RecruitmentSourceMasterDao recruitmentSourceMasterDao;

    @Autowired
    private GradeLookUpDao gradeLookUpDao;

    @Autowired
    private PhotoIdMasterDao photoIdMasterDao;

    @Autowired
    private FileUploadDetailsSer fileUploadDetailsSer;

    @Autowired
    private FileUploadDetailsDao fileUploadDetailsDao;

    @Autowired
    private FileWriter fileWriter;

    @Autowired
    private RegionDetailDao regionDetailDao;

    @Autowired
    private ECDCtool ecdcTool;

    @Autowired
    private NeeDcrypt neeDcrypt;

    @Autowired
    private ManagerController managerController;

    private MockMvc mockMvc;

/*  @Autowired
    private UrlBasedViewResolver urlBasedViewResolver;

    @Autowired
    private TilesConfigurer tilesConfigurer;

    @Autowired
    private TilesView tilesView;
    */

    @Before
    public void setup(){

        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders.standaloneSetup(managerController).build();

        GradeMasterLookUp gradeMasterLookUp = new GradeMasterLookUp();
        gradeMasterLookUp.setGradeName("Manager");

        StateLookUp stateLookUp = new StateLookUp();

        Mockito.when(gradeLookUpDao.getGradeOfLoginUser(null)).thenReturn(gradeMasterLookUp);
        Mockito.when(lookUpSer.getStateLookUps()).thenReturn(Arrays.asList(stateLookUp));
        Mockito.when(loginUsersDao.getAllGradeNameByLoginUserForDataEntry(null)).thenReturn(Arrays.asList("hi world"));
        Mockito.when(lookUpSer.getCityLookUps()).thenReturn(Arrays.asList(new CityLookUp()));
        Mockito.when(lookUpSer.getDesignationLookUps()).thenReturn(Arrays.asList(new DesignationLookUp()));
        Mockito.when(lookUpSer.getDepartmentLookUps()).thenReturn(Arrays.asList(new DepartmentLookUp()));
        Mockito.when(photoIdMasterDao.getPhotoIdMasterList()).thenReturn(Arrays.asList(new PhotoIdMaster()));
        Mockito.when(lookUpSer.getSubDepartmentLookUps()).thenReturn(Arrays.asList(new SubDepartmentLookUp()));
        Mockito.when(recruitmentSourceMasterDao.getRecruitmentSourceMasterList()).thenReturn(Arrays.asList(new RecruitmentSourceMaster()));
        Mockito.when(regionDetailDao.getRegionDetailList()).thenReturn(Arrays.asList(new RegionDetail()));
        Mockito.when(lookUpSer.getAllErcRlgMaster1()).thenReturn(Arrays.asList(new ErcRlgMaster1()));
        Mockito.when(lookUpSer.getLocationLookuUps()).thenReturn(Arrays.asList(new LocationLookuUp()));
        Mockito.when(fileUploadDetailsDao.getDocumentTypeListGreaterThanId(100)).thenReturn(Arrays.asList(new DocumentType()));
    }

    @Test
    public void testMethod() throws Exception{

        EmployeeDetails employeeDetails = new EmployeeDetails();
        employeeDetails.setPanCardNo("lower");
        employeeDetails.setFirstName("Nitesh");

        mockMvc.perform(post("/manager/new")
                .with(user("nitesh")
                .password("nitesh")
                .authorities(AuthorityUtils.createAuthorityList("ADMIN")))
                .contentType(MediaType.ALL)
                .sessionAttr("employeeDetails", employeeDetails)
                )   

                .andExpect(model().attribute("employeeDetails", instanceOf(EmployeeDetails.class)));
    }

    @Test
    public void testNewEmployeeGet()throws Exception{

        mockMvc.perform(get("/manager/newemployee")
                .with(user("nitesh")
                .password("nitesh")
                .authorities(AuthorityUtils.createAuthorityList("ADMIN")))
                .contentType(MediaType.ALL)
                );

    }


    @Configuration
    static class TestManagerControllerContextConfiguration{
        @Bean
        public ManagerController managerController(){
            return new ManagerController();
        }

        @Bean
        public LookUpSer lookUpSer(){
            return Mockito.mock(LookUpSer.class);
        }

        @Bean
        public LoginUsersSer loginUsersSer(){
            return Mockito.mock(LoginUsersSer.class);
        }

        @Bean
        public LoginUsersDao loginUsersDao(){
            return Mockito.mock(LoginUsersDao.class);
        }

        @Bean
        public ManagerService managerService(){
            return Mockito.mock(ManagerService.class);
        }

        @Bean
        public RecruitmentSourceMasterDao recruitmentSourceMasterDao(){
            return Mockito.mock(RecruitmentSourceMasterDao.class);
        }

        @Bean
        public GradeLookUpDao gradeLookUpDao(){
            return Mockito.mock(GradeLookUpDao.class);
        }

        @Bean
        public PhotoIdMasterDao photoIdMasterDao(){
            return Mockito.mock(PhotoIdMasterDao.class);
        }

        @Bean
        public FileUploadDetailsSer fileUploadDetailsSer(){
            return Mockito.mock(FileUploadDetailsSer.class);
        }

        @Bean
        public FileUploadDetailsDao fileUploadDetailsDao(){
            return Mockito.mock(FileUploadDetailsDao.class);
        }

        @Bean
        public FileWriter fileWriter(){
            return Mockito.mock(FileWriter.class);
        }

        @Bean
        public RegionDetailDao regionDetailDao(){
            return Mockito.mock(RegionDetailDao.class);
        }

        @Bean
        public ECDCtool ecdCtool(){
            return Mockito.mock(ECDCtool.class);
        }
        @Bean
        public NeeDcrypt neeDcrypt(){
            return Mockito.mock(NeeDcrypt.class);
        }
    /*  
        @Bean
        public UrlBasedViewResolver urlBasedViewResolver() {
            UrlBasedViewResolver resolver = new UrlBasedViewResolver();
            resolver.setViewClass(TilesView.class);
            return resolver;
        }

        @Bean
        public TilesConfigurer tilesConfigurer(){
            TilesConfigurer tilesConfigurer = new TilesConfigurer();
            tilesConfigurer.setDefinitions("/WEB-INF/tiles/tiles.xml");
            return tilesConfigurer;
        }*/
    }
}

THIS IS MY SPRING CONTEXT WHICH I AM USING TO RUN THE APPLICATION

<beans xmlns="http://ift.tt/GArMu6"
    xmlns:xsi="http://ift.tt/ra1lAU"
    xmlns:context="http://ift.tt/GArMu7"
    xmlns:mvc="http://ift.tt/1bHqwjR"
    xmlns:p="http://ift.tt/1jdM0fE"
    xsi:schemaLocation="http://ift.tt/1bHqwjR http://ift.tt/JWpJWM
        http://ift.tt/GArMu6 http://ift.tt/18sW2ax
        http://ift.tt/GArMu7 http://ift.tt/1bGeTcI">
    <context:component-scan base-package="com.rectrix.ool.controller"></context:component-scan>


    <bean
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations" value="classpath:system.properties" />
    </bean>


    <!-- <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
        <property name="prefix" value="${spring.view.prefix}" /> <property name="suffix" 
        value="${spring.view.suffix}" /> </bean> -->

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass">
            <value> org.springframework.web.servlet.view.tiles2.TilesView
            </value>
        </property>
    </bean>
    <bean id="tilesConfigurer"
        class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
        <property name="definitions">
            <list>
                <value>/WEB-INF/tiles/tiles.xml</value>
            </list>
        </property>
    </bean>

    <bean id="multipartResolver"
        class="org.hdiv.web.multipart.HdivCommonsMultipartResolver" />



    <bean class="org.springframework.web.servlet.view.XmlViewResolver">
        <property name="location">
            <value>classpath:/META-INF/spring/spring-excel-views.xml</value>
        </property>
        <property name="order" value="0" />
    </bean>


<bean id="htmlEscapingObjectMapper" class="com.rectrix.ool.security.HtmlEscapingObjectMapperFactory" />

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" p:objectMapper-ref="htmlEscapingObjectMapper" />
    </mvc:message-converters>
</mvc:annotation-driven>

    <mvc:default-servlet-handler />
    <mvc:annotation-driven />

</beans>

AND THE EXCEPTION IS THROWN IS -

javax.servlet.ServletException: Circular view path [/manager/newemployee]: would dispatch back to the current handler URL [/manager/newemployee] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)
    at org.springframework.web.servlet.view.InternalResourceView.prepareForRendering(InternalResourceView.java:292)
    at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:214)
    at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:264)
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1216)
    at org.springframework.test.web.servlet.TestDispatcherServlet.render(TestDispatcherServlet.java:103)
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1001)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:867)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:844)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:734)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
    at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
    at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:168)
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:136)
    at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:141)
    at com.rectrix.ool.test.controller.TestManagerController.testNewEmployeeGet(TestManagerController.java:182)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

Kindly guide me to overcome this issue. I am really in need .

Aucun commentaire:

Enregistrer un commentaire