moffeltje
moffeltje

Reputation: 4658

How can I programmatically autowire field which is not part of bean?

In a Spring Boot application I am working on, I have a class which is not annotated as bean (@Component), but contains an autowired field:

public class One{
    @Autowired
    private Two x;

    public getX(){
        return x;
    }
}

In the configuration xml of the Spring application the class One is marked as bean which makes that the variable x gets initialized when I run the application.

Now I have written a test that doesn't seem to use the spring xml configuration. So I tried to do it manually:

@RunWith(SpringRunner.class)
public class Test{
    @Autowired
    One y;


    @Test
    public void checkOne(){
        System.out.println(y.getX()); //null
    }
}

How can I make Spring inject the correct code so that x is not null in my test?

Upvotes: 1

Views: 289

Answers (3)

Essex Boy
Essex Boy

Reputation: 7950

Just tell the test what config to use:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContext_test.xml" })
public class Test{
    @Autowired
    One y;

    @Test
    public void checkOne(){
        System.out.println(y.getX()); //null
    }
}

See here for doc

Upvotes: 3

daniu
daniu

Reputation: 14999

Essex Boy's approach runs an "integration test" because it starts up Spring for the test.

Usually for Unit Tests, you want to mock your depencies; those can be "autowired".

@RunWith(MockitoJUnitRunner.class) // necessary for the annotations to work
public class YourTest {

    // this is a mock
    @Mock 
    private Two mockedTwo; 

    @InjectMocks
    // this is automatically created and injected with dependencies       
    private One sut;       

    @Test
    public void test() {
        assertNotNull(sut.getX());
        sut.doStuff();
        verify(mockedTwo).wasCalled();
    }
}

Upvotes: 1

Lesiak
Lesiak

Reputation: 25966

Alernative to @Essex Boy approach: use a custom configuration in your test:

@RunWith(SpringRunner.class)
public class TestClass {

    @Configuration
    @ComponentScan
    static class ConfigurationClass {
        @Bean
        public One makeOne() {
            return new One();
        }
    }

    @Autowired
    One y;


    @Test
    public void checkOne(){
        System.out.println(y.getX()); 
    }
}

Upvotes: 1

Related Questions