I test the following DAO with JUnit:
@Repository
public class MyDao {
@Autowired
private SessionFactory sessionFactory;
// Other stuff here
}
I had same problem with Spring Boot 2.1.1 and JUnit 4
just added those annotations:
@RunWith( SpringRunner.class )
@SpringBootTest
and all went well.
For Junit 5:
@ExtendWith(SpringExtension.class)
source
You need to use the Spring JUnit runner in order to wire in Spring beans from your context. The code below assumes that you have a application context called testContest.xml
available on the test classpath.
import org.hibernate.SessionFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import java.sql.SQLException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.startsWith;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:**/testContext.xml"})
@Transactional
public class someDaoTest {
@Autowired
protected SessionFactory sessionFactory;
@Test
public void testDBSourceIsCorrect() throws SQLException {
String databaseProductName = sessionFactory.getCurrentSession()
.connection()
.getMetaData()
.getDatabaseProductName();
assertThat("Test container is pointing at the wrong DB.", databaseProductName, startsWith("HSQL"));
}
}
Note: This works with Spring 2.5.2 and Hibernate 3.6.5
Add something like this to your root unit test class:
@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration
This will use the XML in your default path. If you need to specify a non-default path then you can supply a locations property to the ContextConfiguration annotation.
http://static.springsource.org/spring/docs/2.5.6/reference/testing.html
Missing Context file location in configuration can cause this, one approach to solve this:
like:
@ContextConfiguration(locations = { "classpath:META-INF/your-spring-context.xml" })
More details
@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration(locations = { "classpath:META-INF/your-spring-context.xml" })
public class UserServiceTest extends AbstractJUnit4SpringContextTests {}
Reference:Thanks to @Xstian
You need to add annotations to the Junit class, telling it to use the SpringJunitRunner. The ones you want are:
@ContextConfiguration("/test-context.xml")
@RunWith(SpringJUnit4ClassRunner.class)
This tells Junit to use the test-context.xml file in same directory as your test. This file should be similar to the real context.xml you're using for spring, but pointing to test resources, naturally.