【问题标题】:Mocking a concrete class in junit 3在junit 3中模拟一个具体的类
【发布时间】:2012-11-10 00:10:08
【问题描述】:

我有一个具有以下构造函数的类:

class Foo {
    Foo (Bar bar) {
       ...
    }
}

我正在尝试为此类编写单元测试并模拟对 Bar 的依赖。但是,我必须使用 JUnit 3 并且 Bar 是一个具体的类型。有没有人有任何想法?我不能使用 EasyMock 类扩展(需要 JUnit 4)并且在 Mockito 上没有成功。我正在考虑的一个(特别难看的)解决方案如下:

interface IBarWrapper {
    void barMethod();
}

class BarWrapper implements IBarWrapper {
    void barMethod() {
        bar.barMethod();
    }
}

class Foo {
    Foo (IBarWrapper wrapper) {
        ...
    }
}

但我不喜欢改变我的实际代码以适应测试的想法。

【问题讨论】:

  • 我怎么没想到?!我猜是因为我没有 6655 的排名 :) 。我认为这是最好的选择。将此添加为答案,我会将其标记为正确。

标签: java testing mocking junit3


【解决方案1】:

你可以只继承Bar。不需要把事情搞得太复杂。

【讨论】:

    【解决方案2】:

    使用EasyMock (v3.x),您可以模拟具体类。见Readme

    【讨论】:

    • 这似乎对我不起作用(NoClassDefFoundError org/objenesis/ObjenesisHelper)。我想我会接受加勒特的建议。还是谢谢你。
    • 缺少一些依赖项。见stackoverflow.com/questions/8258797/…
    猜你喜欢
    • 1970-01-01
    • 2018-02-15
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-11
    相关资源
    最近更新 更多