测试具有带参数的构造函数的抽象类

发布于 2024-10-03 18:17:03 字数 248 浏览 0 评论 0原文

我必须测试正在实现接口之一的抽象类之一。 抽象类有一个带参数的构造函数。 我使用 Mockito 作为测试框架。 那么如果我需要调用抽象类中的方法,最好的方法应该是什么?

如果我尝试子类化抽象类,它会要求实现参数构造函数,并且不允许编写无参数构造函数。 另外,如果我尝试模拟一个没有无参数构造函数的类,并将 sysouts 放入方法中,通常我看不到它们被调用(模拟的类是否需要强制的无参数构造函数?),尽管没有 junit 失败。

请帮忙。提前致谢。

I have to test one of my abstract classes which is implementing one of the interfaces.
The abstract class is having a constructor with arguments.
I am using Mockito as the testing framework.
So if I need to call the methods in the abstract class, what should be the best method?

If I try to subclass the abstract class, its asking to implement the argument constructor and not allowing a no-arg constructor to be written.
Also if I try to mock a class without a no-arg constructor, and put sysouts in the methods, usually I cannot see them invoked (Should the mocked class need a mandatory no-arg constructor ?) although there is no junit failure.

Please help. Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

戏舞 2024-10-10 18:17:21

测试抽象类的一种方法是实现它的具体子类,仅用于测试。

如果抽象类只有一个带参数的构造函数,您可以执行不同的操作:

  • 将 null 传递给其参数
  • 将模拟对象传递给其参数
  • 将具体对象传递给其参数

您选择的方式取决于您的测试用例和抽象类的实现。 - 当然你可以混合使用这些方法。

示例:

abstract class A{
  A(Object o) {
  }
}

class TheNullWay extends A {
  TheNullWay() {
    super(null);
  }
}

class TheMockedWay extends A {
  TheMockedWay(Object o){
    super(o);
  }
}

new TheMockedWay(createMockedObject());

顺便说一句:测试使用抽象类的类是完全不同的事情。

One way to test abstract classes is to implement a concreate subclass of it, only for testing.

If the abstract class has only a construtor with arguments you could do different things:

  • pass null to its arguments
  • pass mocked objects to its arguments
  • pass concrete objects to its arguments

which way you choose depends on your test case and on the implementation of the abstract class. - Of course you could mix the ways.

Example:

abstract class A{
  A(Object o) {
  }
}

class TheNullWay extends A {
  TheNullWay() {
    super(null);
  }
}

class TheMockedWay extends A {
  TheMockedWay(Object o){
    super(o);
  }
}

new TheMockedWay(createMockedObject());

BTW: it is a complete different thing to test a class that uses the abstract class.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文