【问题标题】:Mocked interface is null模拟接口为空
【发布时间】:2011-07-31 16:39:20
【问题描述】:

我正在尝试使用 JMockit 模拟 DAO:

public interface MyDao {
    Details getDetailsById(int id);
}

有了这个测试类:

public class TestClass {

    @Test
    public void testStuff(final MyDao dao) throws Exception
    {
        new Expectations()
        {
            {
                // when we try to get the message details, return our sample
                // details
                dao.getDetailsById((Integer) any);  ***THROWS AN NPE
                result = sampleDetails;
            }
        };

        ClassUsingDao daoUser = new ClassUsingDao(dao);
        // calls dao.getDetailsById()
        daoUser.doStuff();
}

当在 Expectations 块中使用 dao 对象时,会抛出 NPE。我尝试将 dao 的声明移动到使用 @Mocked 注释的成员变量,但同样的事情发生了。我也尝试过使用 MyDao 的具体实现,同样的事情发生了。

【问题讨论】:

  • 不,这个类目前还没有用到Spring,但是以后可能会用在ClassUsingDao中注入dao。

标签: java nullpointerexception unboxing jmockit


【解决方案1】:

不是dao 为空,而是any。从 Integer(在您的演员表之后)到 int 的拆箱涉及取消引用,这会引发 NullPointerException。尝试改用anyInt

我不认为 jMockit 文档讨论了 Expectations.any 的实际值是什么,但请注意它可以成功转换为任何其他类型(您可以说 (String)any(Integer)any)。在 Java 中,所有强制转换总是成功的唯一值是 null。因此,Expectations.any 必须为空。有点意外,但确实不可避免。

【讨论】:

  • 果然如此。感谢您的帮助 - 我花了几个小时来移动它,它就在我面前。谢谢!
猜你喜欢
  • 1970-01-01
  • 2021-07-22
  • 2021-03-10
  • 2014-08-19
  • 2018-05-10
  • 2011-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多