Meena Chaudhary
Meena Chaudhary

Reputation: 10665

Spring Boot Test does not detect static nested @Named component in test class

Following is my class code for test class.

@SpringBootTest(classes = { SpringBootApp.class }, webEnvironment = WebEnvironment.RANDOM_PORT)
public class OuterBeanTest {

    @Inject
    InnerBeanTest innerBean;

    @Test
    public void test() {
         assertThat(this.innerBean.print()).isEqualTo("print");
    }

    @Named
    static class InnerBeanTest {

        String print(){
             return "print";
        }
    };
}

But injection of static class into the test instance throws an error about Unsatisfied dependency expressed through field 'innerBean'; expected at least 1 bean which qualifies as autowire candidate.

How can I inject it into the test instance?

EDIT

OuterBeanTest.java is in com.general package in src/test/java, whereas Spring Boot Application is in com package in src/main/java

SpringBootApp.java

package com;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootApp {

    public static void main(String[] args) {

       SpringApplication.run(SpringBootApp.class, args);
    }
}

NOTE: The same worked Spring-4.2.8 but now I have upgraded to Spring-4.3.7 and it stopped working.

Upvotes: 1

Views: 813

Answers (1)

Sam Brannen
Sam Brannen

Reputation: 31177

The testing support in Spring Boot 1.4 no longer detects static nested components within test classes automatically. This is due to the use of the org.springframework.boot.test.context.filter.TestTypeExcludeFilter behind the scenes.

Thus, you have two options.

  1. Move InnerBeanTest to a top-level class, or...
  2. Annotate OuterBeanTest with @Import(OuterBeanTest.InnerBeanTest.class).

Regards,

Sam

Upvotes: 1

Related Questions