hc0re
hc0re

Reputation: 1996

JUnit4 - @Autowired service is null in @Before annotated method

I have a JUnit test, looking like this:

@RunWith(JUnitParamsRunner.class)
public class ProcessnDbUnitTest extends DbunitTestParent {

    @Autowired
    private ProcessRepositiory pr;

    private static List<Object[]> allProcessIds = new ArrayList<>();

    private static Object[][] result = new Object[allPDRIds.size()][];

    private static List<Process> process = new ArrayList<>();

    @Before
    public void before() {
        processes = pr.findAll();
        pr.findAll().stream().forEach(process -> allProcessIds.add(new Object[] { process.getId() }));
        result = new Object[allProcessIds.size()][];
    }

DbUnitTestParent:

@ContextConfiguration(classes = DbUnitApplication.class)
@RunWith(Suite.class)
@SuiteClasses({UserDbUnitTest.class, ProcessDbUnitTest.class })
public class DbunitTestParent extends AbstractTransactionalJUnit4SpringContextTests {

    @PersistenceContext
    private EntityManager em;

    @After
    public final void flush() {
        em.flush();
    }

}

The test themselves doesn't matter in this case. The fields are static because the @Before method is fetching stuff for a parametrized test.

When I am debugging the test, I see that in the before() method, the autowired ProcessRepository is null. The strange thing is that in another, very similar test, everything works fine... Why could this happen?

Upvotes: 0

Views: 579

Answers (1)

Nicksxs
Nicksxs

Reputation: 104

class aka bean set Autowired Annotation need Spring Context to initialize and manage,if you want to use this annotation, you should use SpringJUnit4ClassRunner, if not you can use Mockito to mock it

Upvotes: 1

Related Questions