Search code examples
javagwtreflectionjunitgwttestcase

GWTTestCase: Testing a Private Method


I am new to GWT / Java and need some ideas on how to solve this (seems like it should be) simple problem.

I have a GWT object and I am trying to test a private method:

public class BarChart extends FlowPanel {

    public BarChart() {
        super();
        privateMethod();
    }

    privateMethod() { 
        //want to test this 
    }
}

I've tried JUnit but it needs to be a GWTTestCase since this object needs GWT.create(), and I've tried reflection but GWTTestCase doesn't support it.


Solution

  • In GWT client (included GWTTestCase), you can call private or protected methods using JSNI, this is known as the violator pattern

    Given a class with a private method

    package com.example;
    public class MyClass {
      private MyObjectReturn myMethod(MyObjectParam param) {
         return null
      }
    }
    

    Create a jsni method and access it

    native MyObjectReturn myViolatorMethod(MyClass instance, MyObjectParam param) /*-{
      return instance.@com.example.MyClass::myMethod(*)(param);
    }-*/;