【问题标题】:Unit Test with Spring JPA - @Autowired is not working使用 Spring JPA 进行单元测试 - @Autowired 不起作用
【发布时间】:2015-11-03 11:51:41
【问题描述】:

我有一个单元测试和一个辅助类。 不幸的是,Helper 类的自动装配不起作用。 它在 MyTest 类中运行良好。

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations={"classpath*:context.xml"})
    @Component
    public class MyTest {

        @Autowired
        private Something something1;

        @Autowired
        private Something something2;
        ..

        @Test
        public void test1()
        {
            // something1 and something2 are fine
            new Helper().initDB();
            ..
        }
   }

// Same package
public class Helper {
   @Autowired
   private Something something1;

   @Autowired
   private Something something2;
   ..

   public void initDB()
    {
        // something1 and something2 are null. I have tried various annotations.
    }
}

我想避免使用 setter,因为我有 10 个这样的对象,并且不同的测试有不同的对象。 那么让@Autowired 在 Helper 类中工作需要什么?谢谢!

【问题讨论】:

标签: spring unit-testing spring-junit


【解决方案1】:

您不能通过new 语句创建Helper 类,但您必须让spring 创建它成为一个spring be,因此它的@Autowired 字段被注入。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath*:context.xml"})
@Component
public class MyTest {

    @Autowired
    private Something something1;

    @Autowired
    private Something something2;
    ..

    @Autowired
    private Helper helper

    @Test
    public void test1() {
        helper.initDB();
    }
}


//this class must been found by springs component scann
@Service
public class Helper {
   @Autowired
   private Something something1;

   @Autowired
   private Something something2;

   public void initDB(){...}
}

【讨论】:

    【解决方案2】:

    你的 Helper 类没有被 spring 实例化...你必须添加一个像 @component 的注解(如果你正在使用包扫描),或者你可以在你的 springconfiguration 类中将类定义为 Bean。但是如果你自己创建实例就不行了

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-26
      相关资源
      最近更新 更多