Anden
Anden

Reputation: 43

Unit Testing a Public method with private supporting methods inside of it?

When trying to perform test driven development on my JSF app, I have a hard time understanding how to make my classes more testable and decoupled.. For instance:

@Test
public void testViewDocumentReturnsServletPath(){
    DocumentDO doc = new DocumentDO();
    doc.setID(7L);
    doc.setType(“PDF”);
    DocumentHandler dh = new DocumentHandler(doc);
    String servletPath = dh.viewDocument();
    assertTrue(servletPath, contains(“../../pdf?path=“);
}

This is only testable (with my current knowledge) if I remove some of the supporting private methods inside viewDocument() that are meant to interact with external resources like the DB.

How can I unit test the public API with these supporting private methods inside as well?

Upvotes: 0

Views: 48

Answers (1)

Ryan Stoughton
Ryan Stoughton

Reputation: 41

Unit testing typically includes mocking of external dependencies that a function relies on in order to get a controlled output. This means that if your private method makes a call to an API you can use a framework like Mockito to force a specific return value which you can then use to assure your code handles the value the way you expect. In Mockito for example, this would look like:

when(someApiCall).thenReturn(someResource);

This same structure holds if you wish to interact with a database or any other external resource that the method you are testing does not control.

Upvotes: 4

Related Questions