2017-05-12 4 views
1

JUnit 4 및 MockMvc를 사용하여 REST 컨트롤러를 테스트하고 있습니다. 몇 주 전에 테스트를 작성하면 모든 것이 예상대로 작동했습니다. 코드에서 일부 수정을했는데 JUnit 테스트를 변경하지 않았습니다. 내 테스트를 실행하기 위해 노력하고있어 때 지금, 나는 오류가 있습니다JUnit 테스트를 실행할 때 ServletContext가 특성 파일을 열 수 없음

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes = MyServerApplication.class) 
@SpringBootTest 
@Transactional 
public class MovieControllerTest { 

    private MockMvc mockMvc; 

    @Autowired 
    private MovieRepository movieRepository; 

    @Autowired 
    private WebApplicationContext wac; 

    @Before 
    public void setup() { 
     this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); 
    } 

    // Some tests 
} 

그리고 내 메인 클래스 :

@SpringBootApplication 
public class MyServerApplication{ 

    public static void main(String[] args) { 
     SpringApplication.run(MyServerApplication.class, args); 
    } 
} 

application.properties 여기

Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/application.properties] 

내 코드입니다 파일은 src/main/resources에 있습니다. 이 파일을 옮기지 않았습니다. 아무 것도하지 않고 서비스에 코드를 추가하고 파일에 일부 속성을 추가했습니다.

나는 이러한 솔루션을 SO 질문 & 문서를 읽고, 시도 :

  • 확인 src/main/resources 것을 내 테스트 클래스 경로에 여전히
  • 내 시험에서 주석 아래 @PropertySource("classpath:application.properties") 추가; 그것은
  • 는 테스트 클래스
  • 대신 기본 클래스에 @PropertySource("classpath:application.properties")을 추가 한 게시물에 제안 내가 @WebAppConfiguration 주석
  • @WebMvcTest 주석을 추가 추가 application.properties 내부의 사본과 함께 src/test/resources을 만들려고 그렇게 작동하지 않았다

물론 이러한 모든 솔루션을 동시에 시도하지는 않았지만 오류가 발생할 때마다 추가 된 코드를 제거했습니다.

테스트 코드가 FileNotFoundException 인 경우에도 문제없이 코드를 실행할 수 있습니다.

해결 방법? 그리고 왜 테스트 클래스에 문제가 있습니까?하지만 서버를 실행할 때 제대로 작동합니까?

+1

서블릿 컨텍스트 (클래스 경로 리소스가 아님)를 찾고 있다는 사실은 당신이하지 말아야 할 일을합니다. 코드의 어딘가에'@PropertySource ("application.properties")를 갖는 것. 또한 문제의 근원 인 스프링 부트 기반 테스트와 함께 @ ContextConfiguration을 사용하지 않아야합니다. –

+0

몇 가지 제안 (정확하게 문제를 해결하지 못할 수도 있음) 1.'@ContextConfiguration'을 필요로하지 않으면'@ SpringBootTest' 주석에 클래스를 지정할 수 있습니다. 2. 컨트롤러 레이어 만 테스트하려면 @ SpringBootTest가 필요하지 않습니다.이 옵션은 전체 응용 프로그램 컨텍스트를로드합니다. '@ WebMvcTest'를 사용하여 테스트 할 컨트롤러를 지정할 수 있습니다 – pvpkiran

답변

0
@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes = MyServerApplication.class) 
@SpringBootTest 
@Transactional 
public class MovieControllerTest { ... } 

테스트 클래스에있는 것입니다. @SpringBootTest을 사용할 때는 @ContextConfiguration을 사용하면 안됩니다 (Spring Boot Reference Guide의 testing chapter 참조).

@RunWith(SpringJUnit4ClassRunner.class) 
@SpringBootTest 
@Transactional 
public class MovieControllerTest { ... } 

수동으로 시도하는 대신 테스트를 위해 스프링 부트를 사용하는 것이 좋습니다. mock mvc 테스트를 위해 Spring Boot 어플리케이션에는 특별한 슬라이스와 설정이 이미 있습니다.

이이 테스트에 @AutoConfigureMockMvc를 추가 할 수 있도록하고 MockMvc 필드에 @Autowired을 넣어 (그리고 @Before 방법 설정을 제거)하십시오.