Whitebox
class provides 'invokeConstructor' method, it is used to invoke the constructor
of a class and get an instance.
Following
are the overloaded forms of invokeConstructor method.
public static <T> T
invokeConstructor(Class<T> classThatContainsTheConstructorToTest,
Class<?>[] parameterTypes, Object[] arguments) throws Exception
public static <T> T
invokeConstructor(Class<T> classThatContainsTheConstructorToTest,
Object... arguments) throws Exception
Above
methods are useful for testing classes with a private constructor.
Following
statements are used to invoke the constructor of a class StringUtil.
StringUtil
stringUtil = Whitebox.invokeConstructor(StringUtil.class, "madam");
Find
the following working application.
StringUtil.java
package com.sample.util; public class StringUtil { private String str; private StringUtil(String str){ this.str = str; } /** * * @param str * @return true if the string is palindrome, else false. */ public boolean isStringPalindrome() { if (str == null || str.isEmpty()) { return true; } return str.equals(new StringBuilder(str).reverse().toString()); } }
StringUtilTest.java
package com.sample.util; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.powermock.reflect.Whitebox; public class StringUtilTest { @Test public void isStringPalindrome_palindrome_true() throws Exception{ StringUtil stringUtil = Whitebox.invokeConstructor(StringUtil.class, "madam"); assertTrue(stringUtil.isStringPalindrome()); } @Test public void isStringPalindrome_palindrome_false() throws Exception{ StringUtil stringUtil = Whitebox.invokeConstructor(StringUtil.class, "madamaa"); assertFalse(stringUtil.isStringPalindrome()); } }
No comments:
Post a Comment