首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用Spring JPA进行单元测试-- @Autowired不起作用

使用Spring JPA进行单元测试-- @Autowired不起作用
EN

Stack Overflow用户
提问于 2015-11-03 19:51:41
回答 2查看 1K关注 0票数 0

我有一个单元测试和一个助手类。不幸的是,Helper类的自动线不能工作。它在MyTest类中运行良好。

代码语言:javascript
复制
    @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个这样的对象,不同的测试有不同的对象。那么,在Helper类中使用@Autowired需要做些什么呢?谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-11-03 19:58:37

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

代码语言:javascript
复制
@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(){...}
}
票数 0
EN

Stack Overflow用户

发布于 2015-11-03 19:55:12

您的Helper类不是由spring实例化的。您必须添加一个类似@component的注释(如果您使用的是package scan),或者您可以在springconfiguration类中将该类定义为Bean。但是,如果您自己创建实例,它将无法工作

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33498433

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档