1

i am trying to setup unit tests for some elements to be used within a spring(-boot) application, and i struggled with setup around ConfigurationProperties and EnableConfigurationProperties. the way i finally got it to work doesn't seem consistent with the examples that i have seen in that i have witnessed needing both ConfigurationProperties and EnableConfigurationProperties on my configuration class, which doesn't seem right, and i was hoping that someone might provide some guidance.

here is a simplified example:

JavaTestConfiguration.java

package com.kerz;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.validation.constraints.NotNull;

@Configuration
@ConfigurationProperties
@EnableConfigurationProperties
public class JavaTestConfiguration {

  public void setFoo(String foo) {
    this.foo = foo;
  }

  @NotNull
  String foo;

  @Bean
  String foo() {
    return foo;
  }
}

JavaTestConfigurationTest.java

package com.kerz;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static org.junit.Assert.assertEquals;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {JavaTestConfiguration.class})
@TestPropertySource("classpath:test.properties")
public class JavaTestConfigurationTest {

  @Autowired
  String foo;

  @Test
  public void shouldWork() throws Exception {
    assertEquals("foo", "bar", foo);
  }
}

test.properties

foo=bar
tony_k
  • 1,983
  • 2
  • 20
  • 27
  • How about using Spring profiles and normal @Configuration classes associated to that profile? In this answer I show a way to do this: http://stackoverflow.com/questions/36635163/spring-boot-externalizing-properties-not-working/36635367#36635367 – Marco Tedone Apr 22 '16 at 06:35

1 Answers1

0

Your test is more integration test if you are starting Spring context. Therefore you should test also production spring configuration.

I would advise not to create testing configuration. Use one production configuration for testing.

You are also using @TestPropertySource annotation, which is used when you need to define test specific properties. If you can test with PROD configuration do not use it.

luboskrnac
  • 23,973
  • 10
  • 81
  • 92