White Box testing aims to test internal methods or part of a component, while Black Box testing aims to test a component, treated as a black box (thus the name) using the public methods provided by this component.
How to Perform Black Box tests?
A JUnit Test Suite (a group of JUnit Test Case s) with a good coverage will test all the public methods provided by a component. Keep in mind that the Black Box test tests the component itself and not it's integration with other component. In order to accomplish that separation, you need to create "mocks" of all components used by your's.
The injection of these mock components can be a little bit tricky if you don't have a public method that does so. In this case the only way for injecting your mock objects will be through Java Reflection as we will discuss later.
How to Perform White Box tests?
As we explained earlier, the White box tests aims at testing specific parts of your components. A well written component that follows Object Oriented will have these specific parts hidden from others outside the component (Encapsulation).
The best way for getting around this is to use Java Reflection to manipulate these parts (usually private methods).
Using Java Reflection for JUnit testing:
It is generally a bad practise to change an access modifier in a method for testing, this violates the contract that should be provided by the component, the component encapsulation and common sense really.
In order to invoke a private method (e.g. in ClassUnderTest imaginary class) we have to use Java Reflection:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
.
.
// Will hold the class types to be sent as parameters to the tested method,
// Leave as null if the method doesn't accept any parameters
Class [] inputClasses= null;
Object[] inputObjects = null;
ClassUnderTest testClass = new ClassUnderTest();
// getDeclaredMethod will return all methods
// (that is including private, public , protected and default)
// getMethod on the other hand, only returns public methods
Method testedMethod = ClassUnderTest.class.getDeclaredMethod("methodName", inputClasses);
// Very important, else you will get an IllegalAccessException
testedMethod.setAccessible(true);
// Assuming the method returns a String, cast as appropriate
String returnValue = (String) testedMethod.invoke(testClass, object);
Thanks for reading.
No comments:
Post a Comment