2017-03-03 3 views
3

디바이스로 Rest 컨트롤러가 있습니다. (디바이스는 resolvem이어야하며 spring-mobile-device를 매개 변수로 사용하고 있습니다). 단위 테스트는 당신이 잘못 요청을 구축하는 테스트 클래스에서RestController를 스프링 모바일 (Spring-mobile-device)로 시작하는 방법

@RequestMapping(method = RequestMethod.POST) 
public ResponseEntity<?> authenticationRequest(@RequestBody AuthenticationRequestDto authenticationRequest, 
     Device device) throws AuthenticationException { 

    Authentication authentication = this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(
      authenticationRequest.getUsername(), authenticationRequest.getPassword())); 
    SecurityContextHolder.getContext().setAuthentication(authentication); 

    UserDetails userDetails = this.userDetailsService.loadUserByUsername(authenticationRequest.getUsername()); 

    String token = this.tokenGenerator.generateToken(userDetails, device); 

    return ResponseEntity.ok(new AuthenticationResponseDto(token)); 
} 

단위 테스트

ResultActions res = mockMvc.perform(post("/auth", authentication, device).contentType(TestUtil.APPLICATION_JSON_UTF8) 
      .content(TestUtil.convertObjectToJsonBytes(authentication))); 
    res.andExpect(status().isOk()); 
+0

'AuthenticationController'와'관련 코드를 넣어 재미있을 수도 있습니다 AuthenticationCont rollerTest'라고합니다. 리포지토리에서 코드를 변경하면 향후 독자를위한 질문 (및 대답)이 무효화됩니다. – g00glen00b

+0

코드를 입력하겠습니다. 감사합니다. – neons

+0

어쩌면 config 클래스에 어딘가에'@ EnableWebMvc' 어노테이션을 추가했는지 확인하십시오. 이것은 모의 MVC가 작동하기 위해서 필요합니다. – g00glen00b

답변

1

기본적으로 저는 제 설정에 잘못되었습니다. 프로덕션 구성과 동일한 방식으로 테스트하도록 Web Config를 구성해야하지만 문법적으로 다릅니다. 이 문제로 MockMVC 설정에 대해 많은 것을 배웠습니다.

스프링 모바일을 사용하여 단위 테스트를 수행하려는 경우 솔루션입니다.

퍼스트 클래스

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes = {WebTestConfig.class}) 
@WebAppConfiguration 
public class WebTestConfigAware { 

    @Autowired 
    private WebApplicationContext context; 

    protected MockMvc mockMvc; 

    @Autowired 
    private FilterChainProxy springSecurityFilterChain; 

    @Before 
    public void setup() { 
    mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); 
    DeviceResolverRequestFilter deviceResolverRequestFilter = new DeviceResolverRequestFilter(); 

    mockMvc = MockMvcBuilders.webAppContextSetup(context) 
     .addFilters(this.springSecurityFilterChain, deviceResolverRequestFilter).build(); 
    } 

} 

2 등석

@Configuration 
@EnableWebMvc 
@Import({RootTestConfig.class, WebCommonSecurityConfig.class}) 
public class WebTestConfig extends WebMvcConfigurerAdapter{ 


    @Override 
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { 
    argumentResolvers.add(new ServletWebArgumentResolverAdapter(new DeviceWebArgumentResolver())); 
    argumentResolvers.add(new SitePreferenceHandlerMethodArgumentResolver()); 
    } 
} 

및 테스트 클래스

public class AuthenticationControllerTest extends WebTestConfigAware { 

    @Test 
    public void testAuthenticationRequest() throws Exception { 
    AuthenticationRequestDto authentication = new AuthenticationRequestDto(); 
    authentication.setUsername("admin"); 
    authentication.setPassword("Test1234"); 

    String jsonAuthentication = TestUtil.convertObjectToJsonString(authentication); 

    ResultActions res = mockMvc.perform(post("/auth") 
     .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE).content(jsonAuthentication)); 

    res.andExpect(status().isOk()); 

    } 
0

의 코드를 나에게 상태 (415)

여기

입니다했다

// a couple of issues here explained below 
ResultActions res = mockMvc.perform(post("/auth", authentication, device).contentType(TestUtil.APPLICATION_JSON_UTF8) 
       .content(TestUtil.convertObjectToJsonBytes(authentication))); 

post("/auth", authentication, device) 인증 및 장치는 경로 URI로 해석되므로 필요하지 않습니다. 여기서 컨트롤러 URI에는 경로 URI 변수가 없습니다. 2 개의 객체를 요청 본문으로 전달하려는 경우 테스트 요청과 컨트롤러 요청 처리기를 수정해야합니다. 당신은 요청의 본문과 같은 두 개체를 전달할 수 없습니다, 당신은 당신이 JSON 객체 문자열을 전달해야 테스트에

@RequestMapping(method = RequestMethod.POST) 
    public ResponseEntity<?> authenticationRequest(@RequestBody AuthenticationRequest request) throws AuthenticationException { 
    AuthenticationRequestDto authenticationDto = request.getAuthenticationDto(); 
    Device device = request.getDevice(); 

    // .... 
} 

또한 컨트롤러에서

class AuthenticationRequest { 
    private AuthenticationRequestDto authenticationDto; 
    private Device device; 

    // constructor, getters and setters 
} 

처럼 하나의 오브젝트를 모두 캡슐화 할 필요가 , 당신은 그것을 바이트로 변환하고 있습니다. (이것이 415를 얻은 이유입니다.) :

// note the change in the TestUtils, the method being called is convertObjectToJsonString (you'll need to add it) 
ResultActions res = mockMvc.perform(post("/auth").contentType(TestUtil.APPLICATION_JSON_UTF8) 
     .content(TestUtil.convertObjectToJsonString(new Authenticationrequest(authentication, device)))); 
+0

안녕하세요, 감사합니다. 너 맞아! 내 URI 문제에 대한하지만 일반적으로 응용 프로그램을 배포 할 때 POSTMAN 사용하여 인증 (사용자 및 암호) 보내고 장치 스프링 구성에 의해 해결됩니다. 잘 모르겠 음 MockMvc에 대한 추가 설정이 필요하거나 모의하려고 시도하면 – neons

+0

좋습니다! 다른 사람들이 비슷한 문제에 직면하면이 답변을 알 수 있도록 내 대답을 수락 할 수 있습니까? – artemisian

+0

물론입니다. 그러나 나는 의견을 바꾼다. 어떤 아이디어? – neons

관련 문제