jerome jerome - 13 days ago 6
Java Question

SpringBoot unit test configuration

I created a spring-boot 1.4.0 application and I would like to internationlize it using yaml file.

I created a class for loading the configuration from the yaml file like it is explained in the documentation here http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-typesafe-configuration-properties.

I would like to create a test to check that my class has correctly loaded the properties from the yaml file.

If we keep the exemple from the documentation how to create a unit test that will load a yaml file (with a different name that application.yml) and check that the method

getUsername()
will return the value from the yaml file ?




Here is the code I have but still can't load the username :

@Component
@ConfigurationProperties(locations = "classpath:mylocalizedprops.yml", prefix="connection")
public class ConnectionProperties {

private String username;

// ... getters and setters

}


and the test class

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class InternationalizationTest {
@Autowired
private ConnectionProperties connectionProperties;

public void propsShouldBeNotNull() {
assertNotNull(connectionProperties);
}

public void userNameShouldBeCorrect() {
assertEquals(connectionProperties.getUsername(), expectedUserName);
}
}


I have failed the userNameShouldBeCorrect test. The file mylocalizedprops.yml is located in the src/main/resources folder of a Maven structured application.

Answer

I would consider this an integration test, not a unit-test because you are testing the interaction between various components. Regardless, here is how I would do it.

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = YourApplication.class)
public class InternationalizationTests() {

  @Autowired
  ConnectionProperties connectionProperties;

  @Test
  public void testCorrectTranslationLoaded() {
    Assert.assertEquals("english-username", connectionProperties.getUsername());
  }    

}

You can also create a test configuration if you would like to, which you can specify which translation to load. You would then need different classes to test different configurations. See the docs: http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html

Comments