Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Mock Parent class for Unit testing

So I have three classes: A, B, C. I need to write unit tests for class A.

  class A extends B{
   //fields go here ...

   public A(String string, ...){
      super.(string,...);
   }
   //other methods here ...
 }

 class B{
   C stuff;
   //other stuff
 }

So C is an important resource (like JDBC or ssh Session). Naturally, I am mocking C. How do I mock B. Imagine B has many children classes that extends it.

My main problem is that A is calling super.(...). I don't want to inject methods into A just for testing. To me that's bad design. Any ideas how to mock the parent?

For example I cannot do class MockB extends B{...} and then try MockB obj = new A(); This would not work because both MockB and A would be children of B.

like image 809
kasavbere Avatar asked Dec 13 '22 00:12

kasavbere


1 Answers

You really shouldn't try to mock the superclass of the class under test. While some mocking frameworks allow "partial mocks" that might make it possible to partially mock the class you're actually testing, it's a bad idea.

If class A and the relation between A and B are sufficiently complex that you think you need this, they should probably not be in an inheritance relation at all.

Consider changing your code so that B delegates to A instead of extending it.

like image 72
Don Roby Avatar answered Dec 26 '22 18:12

Don Roby