2017-05-05 1 views
1

@RunWith & @SpringBootTest을 사용하여 컨트롤러를 테스트하려고합니다. 스프링 부트 1.5.2 컨트롤러 레이어 테스트

<dependency> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter-test</artifactId> 
     <scope>test</scope> 
</dependency> 

테스트

에 대한

컨트롤러

@RestController 
public class HomeController { 

    @RequestMapping(value = "/home", method = RequestMethod.GET) 
    public String get(HttpServletResponse response) throws IOException { 
     return "Hello World"; 
    } 
} 

테스트 클래스

@RunWith(SpringRunner.class) 
@SpringBootTest(classes = Application.class) 
@WebAppConfiguration 
public class SampleTestNGApplicationTests{ 

    @Autowired 
    private TestRestTemplate restTemplate; 

    @Test 
    public void testHome() throws Exception { 

     ResponseEntity<String> entity = this.restTemplate.getForEntity("/home", String.class); 

     assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); 
     assertThat(entity.getBody()).isEqualTo("Hello World"); 
    } 

} 

종속성 지금 @RunWith & @SpringBootTest 주석 내가 그것을 위해 어떤 라이브러리 실종 찾을 수 없습니다? 스프링 부트 1.5.2가 스프링 부트 1.4.2와 비교하면 많이 달라진다는 것을 알고 있습니다.

업데이트 질문 위

는 사실은 내가 테스트를 위해 새 모듈을 만들고 컨트롤러 differnt 한 모듈에, 지금은 해결됩니다. 나는 테스트 모듈의 main-> src-> java 아래에 테스트 코드를 작성 중이며 spring-boot-starter-test 종속성 범위를 종속성으로 표시 했으므로 <scope>test</scope>을 제거했다. 이제 @RunWith & @SpringBootTest 주석을 얻을 수있다.

지금은 오류 @ConditionalOnWebApplication (required) found 'session' scope (OnWebApplicationCondition)

오류 로그

========================= 
AUTO-CONFIGURATION REPORT 
========================= 


Positive matches: 
----------------- 

    DispatcherServletAutoConfiguration matched: 
     - @ConditionalOnClass found required class 'org.springframework.web.servlet.DispatcherServlet'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition) 
     - @ConditionalOnWebApplication (required) found 'session' scope (OnWebApplicationCondition) 

    DispatcherServletAutoConfiguration.DispatcherServletConfiguration matched: 
     - @ConditionalOnClass found required class 'javax.servlet.ServletRegistration'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition) 
     - Default DispatcherServlet did not find dispatcher servlet beans (DispatcherServletAutoConfiguration.DefaultDispatcherServletCondition) 
+0

잘못된 가져 오기가 잘못되었습니다. 말하기 힘듭니다. –

답변

1

같은 것을 할 수있는, 내가 @SpringBootTestwebEnvironment을 추가하고 그것은 나를 위해 노력하고 있습니다.

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 
0
@SpringBootTest(classes = Application.class) 

전체 애플리케이션 컨텍스트를로드 얻고있다. 컨트롤러 레이어 만 테스트하려는 경우에는 필요하지 않습니다. 당신이 그것에 시간의 지출을 많이 한 후이

@RunWith(SpringRunner.class) 
@WebMvcTest(controllers = HomeController.class) 
public class HomeControllerTest { 

    @Autowired 
    private MockMvc mvc; 

    @MockBean 
    private SomeService someservice // Mock any other dependencies which you have in your controller. 

    @Test 
    public void someTest() throws Exception { 

    doAnswer(invocation -> { 
     // return some predefined data which would be returned from your service layer 
    }).when(someservice).someMethod(); 

    mvc.perform(MockMvcRequestBuilders.get("/home").contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) 
     .andExpect(status().isOk()) 
     .andExpect(content().string("expectedString")); 
    } 

} 
+0

SpringBootTest를 제거하고 WebMvcTest를 추가했지만 "ApplicationContext를로드하지 못했습니다." –

+0

@WebAppConfiguration을 제거하고 RestTemplate을 사용하지 않습니다 (이 경우 전체 응용 프로그램 컨텍스트를 설정해야합니다). 예제에 표시된대로 Mockmvc를 사용하십시오. – pvpkiran

관련 문제