Spring控制器模拟测试总是返回200

时间:2017-02-09 10:58:33

标签: java spring spring-mvc spring-test

我花了2天时间解决这个问题。我有一个春季休息应用程序。 无论url是否正确,我总是获得状态200.因此从不使用控制器类(调试不会停止在其内部的制动点) 我遇到的问题是否有任何解决方案? 这是一个WebSecurityConfiguration

@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private AuthenticationSuccessHandler authenticationSuccessHandler;

    @Autowired
    protected void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
        auth.authenticationProvider(authenticationProvider());
    }

    @Bean
    public AuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(userDetailsService);
        authenticationProvider.setPasswordEncoder(passwordEncoder());
        return authenticationProvider;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                    .antMatchers("/", "/login").permitAll()
                    .antMatchers("/logout").authenticated()
                    .antMatchers("/admin**/**").access("hasRole('ADMIN')")
                    .antMatchers("/leader**/**").access("hasRole('LEADER')")
                    .antMatchers("/user**/**").access("hasRole('LEADER') or hasRole('USER')")
                    .antMatchers("/askhelp").authenticated()
                .and()

                .formLogin()
                    .loginPage("/login")
                    .loginProcessingUrl("/login")
                    .successHandler(authenticationSuccessHandler)
                    .failureUrl("/login.html?error=true")
                .and()

                    .logout()
                    .invalidateHttpSession(true)
                    .logoutSuccessUrl("/logout")
                    .deleteCookies("JSESSIONID", "XSRF-TOKEN")
                .and()

                .exceptionHandling()
                    .accessDeniedPage("/access_denied")
                .and()

                .csrf()
                    .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
    }

    private Filter csrfHeaderFilter() {
        return new OncePerRequestFilter() {
            @Override
            protected void doFilterInternal(HttpServletRequest request,
                                            HttpServletResponse response, FilterChain filterChain)
                    throws ServletException, IOException {
                CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class
                        .getName());
                if (csrf != null) {
                    Cookie cookie = WebUtils.getCookie(request, "X-XSRF-TOKEN");
                    String token = csrf.getToken();
                    if (cookie == null || token != null
                            && !token.equals(cookie.getValue())) {
                        cookie = new Cookie("X-XSRF-TOKEN", token);
                        cookie.setPath("/");
                        response.addCookie(cookie);
                    }
                }
                filterChain.doFilter(request, response);
            }
        };
    }


    private CsrfTokenRepository csrfTokenRepository() {
        HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
        repository.setHeaderName("X-XSRF-TOKEN");
        return repository;
    }

    @Bean
    public AuthenticationTrustResolver getAuthenticationTrustResolver() {
        return new AuthenticationTrustResolverImpl();
    }
}

控制器类:

@RestController

public class VillagesController {
    private static final Logger log = LoggerFactory.getLogger(VillagesController.class);
    @Autowired
    VillageService villageService;
    @Autowired
    UserService userService;


    @RequestMapping(value = "/village/{id}", method = RequestMethod.GET)
    public ResponseEntity<Village> getVillageById(@PathVariable(name = "id") String id) {
        Village village = villageService.getById(id);
        if (village == null)
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        return new ResponseEntity<>(village, HttpStatus.OK);
    }

    /**
     * Adds new village in a database.
     * @param village
     * @return added village.
     * @throws JsonProcessingException
     * @throws EntityNotUniqueException
     */
    @RequestMapping(value = "/village/", method = RequestMethod.POST)
    public ResponseEntity<Village> addVillage(@RequestBody Village village) throws JsonProcessingException, EntityNotUniqueException {
        UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
       log.info("I'm here");
        User userByUsername = userService.getUserByUsername(principal.getUsername());
        village.setPlayer(userByUsername.getPlayer());

        if (villageService.isUnique(village)) {
            villageService.add(village);
            log.info("Village added : {}",village);
        }
        return new ResponseEntity<>(village, HttpStatus.CREATED);
    }

    /**
     * Updates village.
     * @param id
     * @param village
     * @return updated village.
     */
    @RequestMapping(value = "/village/{id}", method = RequestMethod.PUT)
    public ResponseEntity<Village> updateVillage(@PathVariable(name = "id") String id, @RequestBody Village village) {
        Village current_village = villageService.getById(id);
        if (current_village != null) {
            current_village.setName(village.getName());
            current_village.setxCoord(village.getxCoord());
            current_village.setyCoord(village.getyCoord());
            current_village.setPopulation(village.getPopulation());
            current_village.setWall(village.getWall());
            current_village.setIsCapital(village.getIsCapital());
            current_village.setUuid(village.getUuid());
            Collections.sort(village.getArmies());
            current_village.setArmies(village.getArmies());
            if (villageService.isUnique(current_village)) {
                villageService.update(current_village);
                log.info("Village updated : {}",current_village);
            }
            return new ResponseEntity<>(current_village, HttpStatus.CREATED);
        }

        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

    @RequestMapping(value = "/village/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<Village> deleteVillage(@PathVariable(name = "id") String id) {
        Village Village = villageService.getById(id);
        if (Village == null) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        villageService.delete(Village);
        return new ResponseEntity<>(Village, HttpStatus.NO_CONTENT);
    }

}

控制器测试

@ContextConfiguration(classes = {WebConfiguration.class, WebSecurityConfiguration.class})
@WebAppConfiguration
public class VillagesControllerTest extends AbstractTestNGSpringContextTests {


    VillageService villageService;

     @Mock
     UserService userService;

    @Autowired
    private WebApplicationContext context;


    @Autowired
    private FilterChainProxy springSecurityFilterChain;



    @InjectMocks
    VillagesController villagesController;

    private MockMvc mockMvc;
    @Spy
    List<Village> alliances = new ArrayList<>();
    @BeforeClass
    public void setUp(){
this.villageService=mock(VillageService.class,withSettings().verboseLogging());
        MockitoAnnotations.initMocks(this);
        this.mockMvc = MockMvcBuilders.webAppContextSetup(context)
                .apply(SecurityMockMvcConfigurers.springSecurity())
//                .addFilters(this.springSecurityFilterChain)
                .build();

    }
    @AfterMethod
    public void resetAllMocks(){
        Mockito.reset(villageService);
    }




    @Test
//    @WithMockUser(username = "trinity",password = "222",roles = {"USER"})
    public void testAddVillage() throws Exception {
        Village village = new Village();
        village.setName("Villkljkj");
        village.setPlayer(new Player());
        village.setxCoord((short) 58);
        village.setyCoord((short) 32);
        village.setArmies(new ArrayList<>());
        village.setIsCapital(true);
        village.setPopulation((short) 500);
        village.setWall((byte) 20);
        village.setUuid("0");


      when(userService.getUserByUsername(anyString())).thenReturn(new ua.cv.tim.model.User());

        doNothing().when(villageService).add(village);

        MockHttpServletRequestBuilder builder =
                MockMvcRequestBuilders.post("/villagkjje")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(convertObjectToJsonBytes(village));
//                        .with(user("trinity").password("222").roles("ADMIN"));
        this.mockMvc.perform(builder)
                .andExpect(unauthenticated())
                .andExpect(MockMvcResultMatchers.status().isCreated());
//                .andDo(MockMvcResultHandlers.print());




  //      ArgumentCaptor<Village> villageArgumentCaptor = ArgumentCaptor.forClass(Village.class);
        verify(villageService, times(1)).add(village);
//        verify(villageService,times(1))
    }


    @Test
//    @WithMockUser(username = "trinity",password = "222",roles = {"USER"})
    public void testUpdateVillage() throws Exception {
        Village village = new Village();
        village.setName("Villkljkj");
        village.setPlayer(new Player());
        village.setxCoord((short) 58);
        village.setyCoord((short) 32);
        village.setArmies(new ArrayList<>());
        village.setIsCapital(true);
        village.setPopulation((short) 500);
        village.setWall((byte) 20);
        village.setUuid("0");
when(villageService.getById("0")).thenReturn(village);
when(villageService.isUnique(village)).thenReturn(true);
        MockHttpServletRequestBuilder builder =
                MockMvcRequestBuilders.post("/village/0")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(convertObjectToJsonBytes(village))
                        .with(user("trinity").password("222").roles("USER")).with(csrf());
        this.mockMvc.perform(builder)
                .andExpect(MockMvcResultMatchers.status().isCreated())
                .andExpect(authenticated())
                .andDo(MockMvcResultHandlers.print());
//        verify(villageService, times(0)).update(village);
    }

    public static byte[] convertObjectToJsonBytes(Object object) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return mapper.writeValueAsBytes(object);
    }

}

0 个答案:

没有答案
相关问题