2015-01-24 2 views
4

저지를 사용하여 설정 한 RESTful API를 테스트하는 게임이 있습니다. Grizzly와 함께 Http 컨테이너를 제공하면서 JUnit을 사용하여 테스트하고 싶습니다.Mockito를 사용하여 Grizzly에서 실행되는 저지 REST API 조롱

는 서버를 사용하여

일반 시험 확인, 즉 요청을 전송 및 수신 응답 등의 API가 CMSApi라고

를 작동하고 그렇게 난 그냥 테스트하고있어 내가 밖으로 조롱하고 싶은 skyService라는 종속성이 api. 그럼 Mockito를 사용하여 만든 mockSkyService 객체를 CMSApi에 어떻게 삽입 할 수 있습니까? 관련 코드는 다음과 같습니다 :

그리 즐 서버가 시작 :

@Before 
public void setUpServer() throws Exception { 

    // start the server and create the client 
    server = Main.startServer(); 

    Client client = ClientBuilder.newClient(); 
    target = client.target(Main.BASE_URI); 
} 

내가 @RunWith(MockitoJUnitRunner.class)를 사용하여 테스트를 실행 :

public static HttpServer startServer() { 
    final ResourceConfig rc = new ResourceConfig().packages("com.sky"); 
    rc.property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true); 
    return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc); 

}

내 JUnit을 위의 시작 메소드를 호출합니다.

@Test 
public void testSaveTile() { 

    //given 
    final Invocation.Builder invocationBuilder = target.path(PATH_TILE).request(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON); 

    Tile tile = new Tile(8, "LABEL", clientId, new Date(), null); 

    //when  
    Response response = invocationBuilder.post(Entity.entity(tile, MediaType.APPLICATION_JSON_TYPE)); 

    //then 
    assertEquals(Status.OK.getStatusCode(), response.getStatus()); 

} 

메이븐 의존성 당신이있어

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 

<modelVersion>4.0.0</modelVersion> 

<groupId>com.sky</groupId> 
<artifactId>sky-service</artifactId> 
<packaging>jar</packaging> 
<version>1.0-SNAPSHOT</version> 
<name>sky-service</name> 

<dependencyManagement> 
    <dependencies> 
     <dependency> 
      <groupId>org.glassfish.jersey</groupId> 
      <artifactId>jersey-bom</artifactId> 
      <version>${jersey.version}</version> 
      <type>pom</type> 
      <scope>import</scope> 
     </dependency> 
    </dependencies> 
</dependencyManagement> 

<dependencies> 
    <dependency> 
     <groupId>org.glassfish.jersey.media</groupId> 
     <artifactId>jersey-media-json-jackson</artifactId> 
     </dependency>   
    <dependency> 
     <groupId>org.glassfish.jersey.test-framework.providers</groupId> 
     <artifactId>jersey-test-framework-provider-bundle</artifactId> 
     <type>pom</type> 
     <scope>test</scope> 

    <dependency> 
     <groupId>org.glassfish.jersey.ext</groupId> 
     <artifactId>jersey-bean-validation</artifactId> 
     </dependency> 
    <dependency> 
     <groupId>org.glassfish.jersey.test-framework.providers</groupId> 
     <artifactId>jersey-test-framework-provider-grizzly2</artifactId> 
    </dependency> 
    <dependency> 
     <groupId>com.sun.jersey</groupId> 
     <artifactId>jersey-json</artifactId> 
     <version>1.16</version> 
    </dependency> 

    <dependency> 
     <groupId>junit</groupId> 
     <artifactId>junit</artifactId> 
     <version>4.10</version> 
     <scope>test</scope> 
    </dependency> 
    <!-- Dependency for Mockito --> 
    <dependency> 
     <groupId>org.mockito</groupId> 
     <artifactId>mockito-all</artifactId> 
     <version>1.9.5</version> 
     <scope>test</scope> 
    </dependency> 
</dependencies> 

<build> 
    <plugins> 
     <plugin> 
      <groupId>org.apache.maven.plugins</groupId> 
      <artifactId>maven-compiler-plugin</artifactId> 
      <version>2.5.1</version> 
      <inherited>true</inherited> 
      <configuration> 
       <source>1.7</source> 
       <target>1.7</target> 
      </configuration> 
     </plugin> 
     <plugin> 
      <groupId>org.codehaus.mojo</groupId> 
      <artifactId>exec-maven-plugin</artifactId> 
      <version>1.2.1</version> 
      <executions> 
       <execution> 
        <goals> 
         <goal>java</goal> 
        </goals> 
       </execution> 
      </executions> 
      <configuration> 
       <mainClass>com.sky.Main</mainClass> 
      </configuration> 
     </plugin> 
    </plugins> 
</build> 

<properties> 
    <jersey.version>2.15</jersey.version> 
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 
</properties> 

답변

5

: 여기

//System Under Test 
private CMSApi cmsApi; 

//Mock 
@Mock private static SkyService mockSkyService; 

이 시험 방법의 호출입니다 : 여기

테스트의 관련 객체 옛것으로 가다. d를 CMSApi에 명시 적으로 등록해야하므로 ResourceConfig을 탭하여 등록하기 전에 조롱 된 SkyService과 함께 주입 할 수 있습니다. 기본적으로 다음과 같이 보입니다.

// Sample interface 
public interface SkyService { 
    public String getMessage(); 
} 

@Path("...") 
public class CMSApi { 
    private SkyService service; 
    public void setSkyService(SkyService service) { this.service = service; } 
} 

// Somewhere in test code 
CMSApi api = new CMSApi(); 
SkyServicer service = Mockito.mock(SkyService.class); 
Mockito.when(server.getMessage()).thenReturn("Hello World"); 
api.setSkyService(service); 
resourceConfig.register(api); 

키는 리소스 클래스가 종속성을 주입하도록 설정 한 것입니다. 더 쉬운 테스트는 의존성 주입의 이점 중 하나입니다. 당신은 생성자, 또는 내가했던 것처럼 세터를 통해 주입하거나 @Inject 주석이있는 주입 프레임 워크를 통해 주입 할 수 있습니다.

저지 DI 프레임 워크 HK2을 사용하는보다 완전한 예제 here을 볼 수 있습니다. Jersey 및 HK2에 대한 자세한 내용은 here을 참조하십시오. 그런 다음 예제에서는 Jersey Test Framework도 사용합니다.이 버전은 이미 종속성을 가지고 있기 때문에이를 활용할 수 있습니다. 여기에 저어지 1을 사용하는 another example이 있지만 개념은 동일하므로 일부 아이디어를 얻을 수 있습니다.

제쳐두고, 내가 익숙한 Jersey 아키타 입을 사용하고있는 것처럼 보입니다. 그래서 당신이 보여주는 설정을위한 코드는 다른 클래스에 있습니다. 현재의 응용 프로그램 구성을 망쳐 놓고 싶지 않을 수도 있습니다. 따라서 가장 좋은 건 테스트 프레임 워크를 사용하고 링크 된 예제에서 볼 수 있듯이 새 구성을 만드는 것입니다. 그렇지 않으면 테스트 클래스에서 리소스 구성에 액세스 할 다른 방법이 필요합니다. 또는 Main 클래스에서 서버를 시작하는 대신 테스트 클래스에 새 서버를 설치할 수 있습니다.

+0

귀하의 회신에 감사 드리며 내가 원하는 것을 얻을 수있었습니다. – raghera

+1

답장을 보내 주셔서 감사합니다. @peeskillet.나는 당신의 예에 따라 일하고 싶었던 것을 얻을 수있었습니다. 결국 나는 할 수 있었다 : - HK2를 사용하여 의존성을 주입하십시오. - JerseyTest 클래스를 확장했습니다. - 모의 서비스 용 팩토리를 만들고 configure() 메서드를 재정 의하여 ResourceConfig에 등록했습니다. 유일한 차이점은 Mockito 주석을 사용하여 모의를 작성하고 테스트 케이스에 스텁 코드를 작성하여 테스트에 필요한 것을 반환 할 수 있다는 것입니다. – raghera