CorayThan
CorayThan

Reputation: 17825

Testing Dao with Spring

I'm having some issues running some tests with the spring junit runner.

I'm using Java configuration for spring, so I can't seem to find an example that works for me.

All I want to do is write a junit test that I can use one of my dao classes in, and have it working with hibernate and everything, but for that I need it to be loaded in a real spring context.

I've tried writing my test class like this:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=HibernateConfig.class, loader=AnnotationConfigContextLoader.class)

public class TestNodeDao {

    @Configuration
    @ComponentScan(basePackages = "com.orclands" )
    static class Config {

        @Bean
        public NodeDao nd() {
            NodeDao nd = new NodeDao();

            return nd;
        }
    }

    @Autowired
    private NodeDao nd;

But it can't autowire in the nodeDao. It says NoSuchBeanDefinitionException.

If I take out the trying to autowire the NodeDao, then it runs, but the whole and only point of running it as a spring test is so I can test the real spring-configured NodeDao.

I also tried it without the component scan, with the component scan but no bean declaration and some other ways, but I couldn't get it to work.

Upvotes: 0

Views: 1067

Answers (1)

Sam Brannen
Sam Brannen

Reputation: 31177

Two things...

  1. There's no need to declare the loader.
  2. As soon as you declare explicit configuration classes, a default (i.e., your nested static configuration class) will no longer be detected.

So try something like this:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={HibernateConfig.class, TestNodeDao.Config.class})
public class TestNodeDao {

  @Configuration
  static class Config {

      @Bean
      public NodeDao nd() {
        return new NodeDao();
      }
  }

  @Autowired
  private NodeDao nd;

  // ...
}

Or perhaps even cleaner:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class TestNodeDao {

  @Configuration
  @Import(HibernateConfig.class)
  static class Config {

      @Bean
      public NodeDao nd() {
        return new NodeDao();
      }
  }

  @Autowired
  private NodeDao nd;

  // ...
}

Regards,

Sam

Upvotes: 1

Related Questions