Mohamed Amine Ouali
Mohamed Amine Ouali

Reputation: 615

Inject @PersistenceContext in test unit for spring

I have problem when injecting entityManager in my test class. I think that this is because i can't load my spring context in my test class.

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'noteDeFraisDAO': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.persistence.EntityManagerFactory' available

this is my test class

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {NoteDeFraisTestConfig.class})
@Transactional

@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
public class NoteDeFraisDAOIT
{
    @Autowired
    private NoteDeFraisDAO noteDeFraisDAO;

    @Test
    public void myTest()
    {

    }

}

And this is the configuration for the test I know that when I use new there will be no inject of entitiesManager define in the dao but I don't know what should I do.

@Configuration
public class NoteDeFraisTestConfig {

    @Bean
    NoteDeFraisDAO noteDeFraisDAO()
    {
        return new NoteDeFraisDAO();
    }
}

I have tried to set my ContextConfiguration to my applicationContext but it didn't work I think that it is because the directory WEB-INF doesn't belong to the classpath. How can I fix this??

This is the structure of my project enter image description here

thanks.

Update

this is my final test class

@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"file:web/WEB-INF/applicationContext.xml", "file:web/WEB-INF/db-config.xml","file:web/WEB-INF/dispatcher-servlet.xml","file:web/WEB-INF/security-config.xml"})
@Transactional
public class NoteDeFraisDAOIT
{
    @Autowired
    private NoteDeFraisDAO noteDeFraisDAO;

    @Test
    public void myTest()
    {

    }

}

Upvotes: 5

Views: 3026

Answers (1)

Sam Brannen
Sam Brannen

Reputation: 31197

Yep, the problem is that the ApplicationContext loaded for your test does not contain the LocalContainerEntityManagerFactoryBean. Assuming that's declared properly in applicationContext.xml, the linked solution below will help.

I have tried to set my ContextConfiguration to my applicationContext but it didn't work I think that it is because the directory WEB-INF doesn't belong to the classpath. How can I fix this??

That's covered here: Location of spring-context.xml

Upvotes: 1

Related Questions