2016-08-08 81 views
1

Wie kann ich meine Profile testen?Spring Boot Profil. Wie testen?

, dass mein Test ist

@Test 
public void testDevProfile() throws Exception { 
    System.setProperty("spring.profiles.active", "dev"); 
    Application.main(new String[0]); 
    String output = this.outputCapture.toString(); 
    Assert.assertTrue(output.contains("The following profiles are active: dev")); 
} 

@Test 
public void testUatProfile() throws Exception { 
    System.setProperty("spring.profiles.active", "uat"); 
    Application.main(new String[0]); 
    String output = this.outputCapture.toString(); 
    Assert.assertTrue(output.contains("The following profiles are active: uat")); 
} 

@Test 
public void testPrdProfile() throws Exception { 
    System.setProperty("spring.profiles.active", "prd"); 
    Application.main(new String[0]); 
    String output = this.outputCapture.toString(); 
    Assert.assertFalse(output.contains("The following profiles are active: uat")); 
    Assert.assertFalse(output.contains("The following profiles are active: dev")); 
    Assert.assertFalse(output.contains("The following profiles are active: default")); 
} 

Mein erster Test führt in Ordnung, aber die anderen nicht.

org.springframework.jmx.export.UnableToRegisterMBeanException: Unable to register MBean [[email protected]6cbe68e9] with key 'requestMappingEndpoint'; nested exception is javax.management.InstanceAlreadyExistsException: org.springframework.boot:type=Endpoint,name=requestMappingEndpoint 

Wie kann ich die Instanz vor dem nächsten Teststart stoppen? Oder welcher ist der bessere Ansatz?

dank

Antwort

4

Ich würde es auf diese Weise tun:

@RunWith(SpringJUnit4ClassRunner.class) 
@SpringApplicationConfiguration(classes = SpringBootApp.class) 
@ActiveProfiles("first") 
public class ProfileFirstTest { 

    @Value("${someProperty}") 
    private String someProperty; 

    @Test 
    public void testProperty() { 
     assertEquals("first-value", someProperty); 
    } 
} 

Der obige Code asumes Sie ein application-first.properties wie dieses:

someProperty=first-value 

Ich würdeKlasse einen Test haben pro Profil, das Sie testen möchten, ist dieses oben für Profil zuerst. Wenn Sie einen Test auf den aktiven Profilen haben müssen (statt einer Eigenschaft), können Sie dies tun:

@Autowired 
private Environment environment; 

@Test 
public void testActiveProfiles() { 
    assertArrayEquals(new String[]{"first"}, environment.getActiveProfiles());  
}