开发者

Test an abstract class having constructor with arguments

开发者 https://www.devze.com 2023-01-26 09:53 出处:网络
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 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 i开发者_JS百科f 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消