2015-04-17 14 views
7

Ho letto molte delle guide su come lavorare con i servizi Spring Boot e RESTful e molti di essi contengono informazioni sui test delle unità in esecuzione, in particolare "Creazione di un'applicazione con Spring Boot". Tuttavia, non ho visto nulla che fornisca un esempio su come testare un'unità un'applicazione Spring Boot che consuma/dipende da altre applicazioni Spring Boot, come è comune nell'architettura dei micro-servizi cloud. Così, per esempio, abbiamo i seguenti servizi: Primavera BootTest di integrazione Microservices basati su Spring Boot

ServiceMediator, adapter1, adapter2

ServiceMediator chiama adapter1 o adapter2, a seconda dell'ingresso.

C'è un modo per avviare i servizi Spring Boot Adapter1 e Adapter2 prima di avviare e testare ServiceMediator in un test JUnit Spring?

+0

Sei Parlando di unità test dove si sarebbe deridere il servizioMediator o si desidera fare un test di integrazione su dove si chiama il servizio reale? – ndrone

+0

I test di integrazione sono ciò di cui sto parlando. – LouRoy

+0

Immagino che dipenda davvero da come lo definisci. Sto semplicemente cercando un modo per testare tutti i servizi sul mio computer locale in modo automatico. Quindi, c'è un modo per avviare i servizi che il mediatore dipende prima di testare il mediatore? – LouRoy

risposta

1
package controller; 


import static org.junit.Assert.assertThat; 

import java.io.File; 
import java.net.URL; 

import mediator.CLPApplication; 

import org.hamcrest.Matchers; 
import org.junit.After; 
import org.junit.Before; 
import org.junit.Test; 
import org.junit.runner.RunWith; 
import org.springframework.beans.factory.annotation.Value; 
import org.springframework.boot.test.IntegrationTest; 
import org.springframework.boot.test.SpringApplicationConfiguration; 
import org.springframework.boot.test.TestRestTemplate; 
import org.springframework.http.ResponseEntity; 
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 
import org.springframework.test.context.web.WebAppConfiguration; 
import org.springframework.web.client.RestClientException; 
import org.springframework.web.client.RestTemplate; 

@RunWith(SpringJUnit4ClassRunner.class) 
@SpringApplicationConfiguration(classes = CLPApplication.class) 
@WebAppConfiguration 
@IntegrationTest() 
public class ControllerTest { 

    @Value("${adapter.dependency.jar.location}") 
    private String adapterDependencyJarLocation; 

    @Value("${adapter.dependency.jar.name}") 
    private String adapterDependencyJarName; 

    @Value("${adapter.url}") 
    private String adapterURL; 

    @Value("${mediator.url}") 
    private String mediatorURL; 

    private URL mediator; 
    private URL adapter; 
    private RestTemplate template; 
    Process process = null; 

    @Before 
    public void setUp() throws Exception { 

     adapter = new URL(adapterURL); 
     template = new TestRestTemplate(); 

     // 
     // Start the Atomic adapter 
     // 
     System.out.println(adapterDependencyJarLocation); 
     System.out.println("Starting Adapter"); 

     try { 
      process = new ProcessBuilder("java", "-jar", adapterDependencyJarName) 
       .directory(new File(adapterDependencyJarLocation)).start(); 

      // Try connecting 5 times with a 5 second pause between each 
      // to see if it started. 
      Thread.sleep(5000); 
      for(int i = 0; i <= 5; i++) { 
       try{ 
        System.out.println("Testing to see if Adapter is up"); 
        template.getForEntity(adapter.toString(), String.class); 
        System.out.println("Adapter Started"); 
        break; 
       } 
       catch(RestClientException rce){ 
        System.out.println("It's not up yet"); 
       } 
       Thread.sleep(5000); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    @Test 
    public void testMediator() throws Exception { 
     mediator = new URL(mediatorURL); 
     System.out.println("Calling Mediator"); 
     ResponseEntity<String> response = template.getForEntity(mediator.toString(), String.class); 
     System.out.println(response.getBody()); 
     // Getting back JSON, so check to see if it starts with an open bracket 
     assertThat(response.getBody(), Matchers.startsWith("{")); 
    } 

    @After 
    public void tearDown() { 
     if(process != null) { 
      process.destroy(); 
     } 
    } 
} 
4

Il process-exec-maven-plugin potrebbe essere utile permette di avviare processi multipli Java a pre-integrazione-test fase (come le app Primavera di avvio standard), e prende automaticamente cura di loro arresto in post- fase di integrazione.

NOTA: Il test di integrazione deve essere eseguito al integrazione-test di fase per il Maven-fail-safe-plugin dovrebbe essere configurato con primavera-boot-maven-pluginsee. Poi fare le prove di integrazione verifica o superiore maven ciclo di vita deve essere mirata, perché il integrazione-test fase è infatti situato tra pacchetto e verificare Lifecycles see Default Lifecycles.

Il seguente Maven (pom.xml) Configurazione funzionato per me:

<build> 
    <plugins> 
     <plugin> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-maven-plugin</artifactId> 
      <version>1.3.5.RELEASE</version> 
      <executions>      
       <execution> 
        <id>pre-integration-test</id> 
        <goals> 
         <goal>start</goal> 
        </goals> 
        <configuration> 
         <skip>${integration-tests.skip}</skip> 
        </configuration> 
       </execution> 
       <execution> 
        <id>post-integration-test</id> 
        <goals> 
         <goal>stop</goal> 
        </goals> 
        <configuration> 
         <skip>${integration-tests.skip}</skip> 
        </configuration> 
       </execution> 
      </executions> 
     </plugin>   

     <plugin> 
      <groupId>org.apache.maven.plugins</groupId> 
      <artifactId>maven-failsafe-plugin</artifactId> 
      <version>2.19.1</version> 
      <configuration> 
       <skip>${integration-tests.skip}</skip>     
       <includes> 
        <include>**/*IT.java</include> 
       </includes> 
      </configuration> 
      <executions> 
       <execution> 
        <goals> 
         <goal>integration-test</goal> 
         <goal>verify</goal> 
        </goals>       
       </execution>      
      </executions> 
     </plugin> 

     <plugin> 
      <groupId>com.bazaarvoice.maven.plugins</groupId> 
      <artifactId>process-exec-maven-plugin</artifactId> 
      <version>0.7</version> 
      <executions>      
       <execution> 
        <id>switchboard-process</id> 
        <phase>pre-integration-test</phase> 
        <goals> 
         <goal>start</goal> 
        </goals> 
        <configuration> 
         <name>accounts-service</name> 
         <workingDir>/../../micro-service</workingDir> 
         <waitForInterrupt>false</waitForInterrupt>       
         <arguments> 
          <argument>java</argument> 
          <argument>-jar</argument> 
          <argument>${basedir}/../micro-service/target/micro-service-${project.version}-exec.jar</argument> 
         </arguments> 
        </configuration> 
       </execution> 
       <!--Stop all processes in reverse order--> 
       <execution> 
        <id>stop-all</id> 
        <phase>post-integration-test</phase> 
        <goals> 
         <goal>stop-all</goal> 
        </goals> 
       </execution> 
      </executions> 
     </plugin> 
    </plugins> 
</build> 

Avere una classe Integration Test (WebServerIT) in test.java cartella:

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; 

@RunWith(SpringJUnit4ClassRunner.class) 
@SpringApplicationConfiguration(classes = WebServerApp.class) 
@WebIntegrationTest("server.port:0") 
public class WebServerIT { 

    @Autowired 
    private WebApplicationContext webServerAppContext; 

    private MockMvc webServerMockMvc; 

    @Before 
    public void setUp() { 
     System.out.println("the test is set up"); 
     webServerMockMvc = MockMvcBuilders.webAppContextSetup(webServerAppContext).build(); 
    } 

    /** 
    * This test calls the WebServer's endpoint (/accounts/123456789) which in turn calls the micro-service rest api 
    * which is started using the process-exec-maven-plugin, otherwise the test would fail. 
    */ 
    @Test 
    public void testWebServerInteractionWithMicroService() throws Exception { 
     this.webServerMockMvc.perform(get("/accounts/123456789")) 
       .andExpect(status().isOk()); 
    } 
} 
Problemi correlati