0

I am not very familiar with Unit Tests, I know that they are very important for code quality, and I want to write some in my project. I recently run into some issues. The context is that, I am writing the testClassA for my Aclass, but some functions in Aclass depend on BClass.

BClass is a utility function, so it has many public static function. AClass uses Bclass's functions :

public class Aclass{

    public boolean Afunction()
    {
        String result = Bclass.Bfunction();
        //do stuff with result
        return true
    }

}

public class Bclass{

    public static String Bfunction()
    {
        //function code
    }

}

I want that everytime the BClass.Bfunction is called, then I can return what I want without really execute the real Bfunction in Bclass, so my Aclass doesn't depend on other class in my test. Is it possible ?

Jeroen
  • 1,168
  • 1
  • 12
  • 24
W.Qindi
  • 15
  • 1
  • 4
  • Here's an example of mocking a static method: http://stackoverflow.com/questions/10583202/powermockito-mock-single-static-method-and-return-object – Willcodeforfun Aug 19 '16 at 15:36

1 Answers1

0

One approach that limits your changes to just the Aclass, and eliminates the dependency on Bclass (as you asked for) is extract-and-override:

  1. Identify the code you wish to bypass in your test and extract it to a method.
  2. Override that method in a sub-class of your class-under test. In this overidden method, you can code whatever mock behavior is appropriate for the test:

So your modified Aclass would look like this:

public class Aclass {
    public boolean Afunction() {
         String result = doBfunction();
         // do stuff with result
         return true;
    }
    // This is your "extracted" method.
    protected doBfunction() {
        return Bclass.Bfunction();
    }
}

and your test class would look like this:

class AClassTest {

    @Test
    public void testAFunction() {
         Aclass testObject = new TestableAclass();
         boolean value = testObject.AFunction();
         // now you can assert on the return value
    }

    class TestableAclass extends Aclass {
        @Override
        protected String doBfunction() {
             // Here you can do whatever you want to simulate this method
             return "some string";  
        }
    }
}
EJK
  • 12,332
  • 3
  • 38
  • 55