Robert Mark Bram
Robert Mark Bram

Reputation: 9693

Invoking a private method via JMockit to test result

Am using JMockit 1.1 and all I want to do is invoke a private method and test the return value. However, I am having trouble understanding exactly how to do this from the JMockit De-Encapsulation example.

The method I am trying to test is the private method in this class:

public class StringToTransaction {
   private List<String> parseTransactionString(final String input) {
      // .. processing
      return resultList;
   }
}

And my test code is below.

@Test
public void testParsingForCommas() {
   final StringToTransaction tested = new StringToTransaction();
   final List<String> expected = new ArrayList<String>();
   // Add expected strings list here..
   new Expectations() {
      {
         invoke(tested, "parseTransactionString", "blah blah");
         returns(expected);
      }
   };
}

And the error I am getting is:

java.lang.IllegalStateException: Missing invocation to mocked type at this point; please make sure such invocations appear only after the declaration of a suitable mock field or parameter

Perhaps I have misunderstood the whole API here, because I don't think I want to mock the class.. just test the result of calling the private method.

Upvotes: 18

Views: 33612

Answers (6)

Rohit Gaikwad
Rohit Gaikwad

Reputation: 3914

As mocking private methods is not allowed in latest Jmockit. One can mock the APIs used inside that private method as a Workaround instead of mocking the private method.

This workaround can also be treated as a final solution.

Example:
Actual Class:

class A {

  private int getId(String name){  //private method
      return DAOManager.getDao().getId(name);  //Call to non-private method can be mocked.
  }
}  

Test Class:

public class ATest{

  @Before
  public void setUp(){
    new MockDAOManager();
  }

  //Mock APIs used by the private method `getId`.
  public static class MockDAOManager extends MockUp<MockDAOManager>{
     static mocked_user_id = 101;

     @Mock
     public DAOManager getDao() throws Exception{
          return new DAOManager();
     }

     @Mock
     public Integer getId(String name){
         return mocked_user_id;
     }
  }
}

Note:

  • If you don't have such logic(private method calls to another non-private method) then you may have to refactor your code, Otherwise this will not work.
  • Here DAOManager.getDao().getId(name) is not a private API.
  • There may be a need to mock all APIs used by that private method.

Upvotes: 2

Abhishek Ransingh
Abhishek Ransingh

Reputation: 217

As mentioned by @Jeff Olson, you can also call the private methods of a bean by declaring them @Tested.

Here is an example:

// Java

    @Tested
    private YourServiceImplClass serviceImpl;

    @Test
    public void testPrivateMethod() {
   
          List<String> expected = new ArrayList<String>();
          // Add expected strings list here..

          List<String> actual = Deencapsulation.invoke(serviceImpl, "yourPrivateMethod", "arguments");
          assertEquals(expected, actual);
    }

Upvotes: 0

zinking
zinking

Reputation: 5685

start from 1.35(?) jmockit removed that helper method. for reasons that it is no longer useful (which I don't quite understand)

but yes, this utility is available somewhere else

org.springframework.test.util.ReflectionTestUtils

Upvotes: 0

Jeff Olson
Jeff Olson

Reputation: 6463

I think you are making this too complicated. You should not be using the Expectations block at all. All you need to do is something like this:

@Test
public void testParsingForCommas() {
   StringToTransaction tested = new StringToTransaction();
   List<String> expected = new ArrayList<String>();
   // Add expected strings list here..

   List<String> actual = Deencapsulation.invoke(tested, "parseTransactionString", "blah blah");
   assertEquals(expected, actual);
}

Basically, call a private method via Deencapsulation and test that the actual is equal to the expected. Just like you would if the method were public. No mocking is being done, so no Expectations block is needed.

Upvotes: 39

Robert Mark Bram
Robert Mark Bram

Reputation: 9693

At this point, I don't know if JMockit can or should be used for this. Testing my private method can be done with plain old reflection, although I started this exercise to learn about JMockit (and test my code). In case JMockit cannot be used for this, here is how I can use reflection instead.

@Test
public void testParsingForCommas() throws Exception {
   StringToTransaction tested = new StringToTransaction();
   ArrayList<String> expected = new ArrayList<>();
   expected.add("Test");

   Method declaredMethod =
         tested.getClass().getDeclaredMethod("parseTransactionString",
               String.class);
   declaredMethod.setAccessible(true);
   Object actual = declaredMethod.invoke(tested, "blah blah");
   assertEquals(expected, actual);
}

The call to setAccessible(true) is important here or the invoke will blow up when calling a private method.

declaredMethod.setAccessible(true);

But you want to know what is really cool? If you don't call setAccessible(true), it will blow up with a java.lang.StackOverflowError! :)

Upvotes: 4

Ankur Shanbhag
Ankur Shanbhag

Reputation: 7804

Why do you want to test the private method directly ? Most of the times API methods i.e. public interface methods are unit tested as private methods will be be indirectly tested as well along with them. You can put assert statements with expected values from private methods where you call them within the public methods. So if assert fails you are sure that there is some issue with the private method. So you need not test it separately.

Upvotes: -2

Related Questions