简体   繁体   中英

Unit test with wrapped public static method Java

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 ?

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";  
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM