Platinum Partner

JUnit Testing Private Method

// 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);
			}
		}
	}
{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}