The Artima Developer Community
Sponsored Link

Java Buzz Forum
Testing Private Methods

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Erik C. Thauvin

Posts: 4232
Nickname: ethauvin
Registered: Apr, 2004

Erik C. Thauvin maintains one of the web's first and most popular linkblogs.
Testing Private Methods Posted: Jan 29, 2006 2:53 AM
Reply to this message Reply

This post originated from an RSS feed registered with Java Buzz by Erik C. Thauvin.
Original Post: Testing Private Methods
Feed Title: Erik's Weblog
Feed URL: http://erik.thauvin.net/blog/feed.jsp?cat=Java
Feed Description: The Truth is Out There!
Latest Java Buzz Posts
Latest Java Buzz Posts by Erik C. Thauvin
Latest Posts From Erik's Weblog

Advertisement
[@418]

Testing Private Methods

I've been playing with TestNG for a few days now. I really like it. It makes me want to write more tests.

I was wondering if there was a way to create a test for a private method, so I went to the source. I asked Cédric about it. He mentioned that I should use the Reflection API.

The goal was to write a test for the validate method in the following class:

package net.thauvin.erik;

public class Example {
  // ...
  
  private static int validate(String username, String password, int days) {
    // ...
    
    return days;
  }
}
In order to invoke the validate method in my test, I simply needed to: as follows:
package net.thauvin.erik;

import org.testng.annotations.*;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ExampleTest {
  // ...

  @Test
  public void validateTest() throws NoSuchMethodException,
      IllegalAccessException, InvocationTargetException {
    final Method validate = Example.class.getDeclaredMethod("validate",
        String.class, String.class, int.class);
    validate.setAccessible(true);

    assert (new Integer(10).equals(validate.invoke(validate, "test",
        "passw0rd"new Integer(10))));
  }
}
Pretty nifty trick.

Tags:  , ,

Read: Testing Private Methods

Topic: [Jan 17, 2006 09:54 PST] 4 Links Previous Topic   Next Topic Topic: Faster, simpler return statements

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use