【问题标题】:Why is this DAO in spring returning a null pointer [duplicate]为什么这个DAO在春天返回一个空指针[重复]
【发布时间】:2016-02-15 21:39:10
【问题描述】:

试图从 junit 测试中调用一个非常简单的方法。 我有一个接口和类:

public interface CacheSampleDao {
    String sample(String a);
}

public class CacheSampleImpl implements CacheSampleDao {
    public String sample(String a) {
        return "1";
    }
}

这个类也是我的context.xml中的一个bean

    <bean class="com.premierinc.datascience.repo.CacheSampleImpl"/>

还有一个测试

@Test
public class CacheSampleTest extends AbstractTest {
    @Autowired CacheSampleDaoImpl cacheSampleDaoImpl;
    @Test
    public void cacheTest() {
        String a = cacheSampleDaoImpl.sample("A");
    }
}

为什么这个测试会给出空指针异常?是否有一些其他相关的配置需要为此或我缺少的其他步骤完成?

【问题讨论】:

  • 您的测试没有任何注释?
  • 如何在测试中设置 Spring 上下文(我认为这就是 @JérémieB 的意思)——AbstractTest 中是否有任何 @RunWith 注释?如果没有,您希望如何注入cacheSampleDaoImpl
  • CacheSampleTest 有一个 Test 注释,我只是在此处进行了编辑以显示它。亚当,我没有 @RunWith 注释,我正在研究它
  • @JérémieB 是的,我添加了该注释,然后修复了我的 pom 的一个问题,然后做了一个 mvn clean 并且现在更好了。我最终会想出来的!

标签: java spring junit


【解决方案1】:

使用界面很好。 您遇到的问题是因为您@Autowired 声明是:

 @Autowired CacheSampleDaoImpl cacheSampleDaoImpl;

但是你的 DaoImpl 在哪里?你创建的bean是一个CacheSampleImpl,它实现的是CacheSampleDao接口,而不是DaoImpl。

此外,该属性应根据您创建的 bean 命名,您没有名为 cacheSampleDaoImpl 的 bean 或类型为 CacheSampleDaoImpl 的 bean,以便自动装配成功解决。

根据您显示的代码(不包括 CacheSampleDaoImpl),我相信您想要的是:

@Autowired CacheSampleDao cacheSampleImpl;

这里有一篇关于如何做到这一点的好帖子:

Spring autowire interface

【讨论】:

  • 如果您阅读评论,您会发现问题比这更简单。我怀疑这个名字是对stackoverflow错误的剪切/粘贴;-)
  • 是的,这是一个剪切/粘贴问题,我的错。
【解决方案2】:

对于使用 spring 的集成测试,您应该关心将 spring 上下文插入到测试中,在其他情况下,没有什么会关心 bean 的构建和注入,这实际上发生在您的测试中。 作为一种解决方案,您可以使用以下注释来注释您的测试:@ContextConfiguration 和 @RunWith,如下所示:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/your-spring-context.xml")

您可以在 spring 参考文档中了解有关 spring 测试的更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-16
    • 2022-01-02
    • 2012-10-02
    • 2011-08-24
    • 1970-01-01
    • 1970-01-01
    • 2022-12-03
    • 1970-01-01
    相关资源
    最近更新 更多