1

I have working JUnit tests for my MVC controllers. Now I wanted to display the build number in the footer of every page, so I added the following div in my thymeleaf templates:

<div class="versionInfo">Version <span th:text="${@buildProperties.getVersion()}"></span></div>

Now the test fail with:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'buildProperties' available

I tried to add it as a mock to no avail:

@MockBean
private BuildProperties buildProperties;

Or following this advice (see my comment below the answer).

So how can I make my tests work again with the BuildProperties?

Thomas
  • 6,325
  • 4
  • 30
  • 65

3 Answers3

1

When you try to access a bean via the following way: ${@buildProperties.getVersion()} it's actually a SpEL expression for accessing a bean via a BeanReference. Unfortunately it has no default value and instead of returning null it throws an exception if the bean cannot be found.

I don't know any easy way to check if a bean exists in the context via SpEL.

So I think the best solution if you create a nested test configuration class and define a default BuildProperties bean there.

@TestConfiguration
public static class TestConfig {    
  @Bean 
  BuildProperties buildProperties() {
    return new BuildProperties(new Properties());
  }
}

Or you can create it as a separate class and use @Import(TestConfig.class) if you need this extra configuration in multiple test classes.

Selindek
  • 3,269
  • 1
  • 18
  • 25
0

If you are using gradle , just add this to your build.grandle file:

SpringBoot { buildInfo() }

After configuring the spring-boot-maven-plugin you can build the application and access information about application’s build. The BuildProperties object is injected by Spring (@Autowired)

  • Thanks, but the basic logic is working if I call the page in a browser, but my problem is with the JUnit test of my MVC Tests. – Thomas Feb 15 '19 at 15:48
0

Changing the @WebMvcTest to a full blown @SpringBootTest would fix the problem, because then the ProjectInfoAutoConfiguration would be executed. As I wanted to stick to @WebMvcTest, I included the ProjectInfoAutoConfiguration to my WebMvcTest:

@WebMvcTest(YOUR_CONTROLLER_HERE.class)
@ImportAutoConfiguration(ProjectInfoAutoConfiguration.class)
class YOUR_CONTROLLER_HERETest{
    // Use at your will
    @Autowired
    private BuildProperties buildProperties;
}

Of course, this will only work, if the Spring Boot Maven Plugin is correctly configured.

joecracker
  • 509
  • 5
  • 7