Unable to mock Service class in Spring MVC Controller tests

后端 未结 7 784
渐次进展
渐次进展 2020-12-02 06:44

I have a Spring 3.2 MVC application and am using the Spring MVC test framework to test GET and POST requests on the actions of my controllers. I am using Mockito to mock the

7条回答
  •  伪装坚强ぢ
    2020-12-02 07:20

    I would prefer standalone service of Mockmvc

    Mentioned work for me

    public class AccessControllerTest {
    
        private MockMvc mockMvc;
    
        @Mock
        private AccessControlService accessControlService;
    
        @InjectMocks
        private AccessController accessController;
    
        @Before
        public void setup() {
            MockitoAnnotations.initMocks(this);
            this.mockMvc =  MockMvcBuilders.standaloneSetup(accessController).build();
        }
    
        @Test
        public void validAccessControlRequest() throws Exception {
            Bundle bundle = new Bundle();
            bundle.setAuthorized(false);
            Mockito.when(accessControlService.retrievePatient(any(String.class)))
             .thenReturn(bundle);
    
            mockMvc.perform(get("/access/user?user=3")).andExpect(status().isOk());
    }
    

提交回复
热议问题