-1

I am very new to Java Spring and I tried to set up 2 classes and a Test for one of them. That is my project structure:

enter image description here

Here is the code for the classes:

@Component
public class Box {

    private Item item;

    @Autowired
    public Box(Item item) {
        this.item = item;
    }

    public Item getItem() {
        return item;
    }
}
@Configuration
@ComponentScan
public class BoxConfig {}
@Component
public class Item {}

And here is the code of the JUnit Test I wrote in the BoxTest class:

@ContextConfiguration(classes = {BoxConfig.class})
public class BoxTest {

    @Autowired
    Box box;

    @Test
    public void BoxTest1() {
        Assertions.assertNotNull(box.getItem());
    }
}

My Expectation was, that Spring automatically injects a box object into the box attribute of the Test, but the box attribute ist always null so I keep getting a NullReferenceException. Does someone know why it is not properly initialised?

Cake
  • 90
  • 1
  • 8

1 Answers1

1

BoxTest needs to be included in Spring configuration somehow. E.g. using @ExtendWith(SpringExtension.class) would help.

You can look at other options in Spring documentation.

Krzysztof Krasoń
  • 26,515
  • 16
  • 89
  • 115
  • That worked, thank you very much. But what exactly is the problem when I don't have that line? – Cake Mar 07 '23 at 14:05
  • 1
    Without that line Spring doesn't know that you have a class that needs injection. Similarly how if you had a non-test class without e.g. Component annotation but an Autowired field inside. That field would be always set to default value (unless of course you would create a bean in another way). – Krzysztof Krasoń Mar 07 '23 at 14:09