DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Katarina has posted 8 posts at DZone. View Full User Profile

JUnit Testing Private Method

11.28.2010
| 3004 views |
  • submit to reddit
        // JUnit testing private method

	@Test
	public final void testPrivateMethod() {
		try {
			String methodName = "privateMethodName";

			Class<?>[] parameterTypes = new Class[2];
			parameterTypes[0] = Errorable.class;
			parameterTypes[1] = String.class;

			Errorable errorable = setUpErrorable();

			Object[] parameters1 = { errorable, "foo" };
			invokePrivateMethod(methodName, parameters1);
			SmsRecordContext smsRecordContext = (SmsRecordContext) errorable;
			assertEquals(expected, actual);

			Object[] parameters2 = { errorable, "" };
			invokePrivateMethod(methodName, parameters2);
			smsRecordContext = (SmsRecordContext) errorable;
			assertEquals(expected, actual);;

			Object[] parameters3 = { errorable, null };
			invokePrivateMethod(methodName, parameters3);
			smsRecordContext = (SmsRecordContext) errorable;
			assertEquals(expected, actual);

		} catch (Exception e) {
			e.printStackTrace();
			fail(e.getMessage());
		}
	}

	private void invokePrivateMethod(String methodName, Object[] parameters) throws IllegalAccessException, InvocationTargetException {
		Method[] classContainingPrivateMethodMethods;
		classContainingPrivateMethodMethods = classContainingPrivateMethod.getClass().getDeclaredMethods();
		for (int i = 0; i < classContainingPrivateMethodMethods.length; ++i) {
			if (methodName.equals(classContainingPrivateMethodMethods[i].getName())) {
				classContainingPrivateMethodMethods[i].setAccessible(true);
				classContainingPrivateMethodMethods[i].invoke(classContainingPrivateMethod, parameters);
			}
		}
	}