1

I am new writing good test cases, so please bear with me. Writing a test case for private methods

public Stock getStock(String stockTicker) {
            Stock company = new Stock();
            String url = getEndpointURL(stockTicker);
            htmlDocument = fetchHTMLDocument(url); // private method
            company.name = getStockName(); // private method uses htmlDocument
            company.actualPrice = getActualPrice(); // private method uses htmlDocument
            return company;
    }

Current Test case looks like

assertThat(selector.getActualPrice()).isGreaterThan(-1);
assertThat(selector.getStockName()).isNotNull();

But this doesn't allow me to make methods private..

To make the methods private, and since I want to test getStock only using public methods (like recommended in "How do you unit test private methods?"), I want to write test case for getStock method as below

Stock st = selector.getStock("AAPL");
assertThat(st.name).isNotNull();

i.e make assertions on Stock object

However, in this test, I want to avoid the backend call made by fetchHTML() and pass a custom Document to test the functioning of getStockName() and getActualPrice() method.

How do I do this without making methods public?

Doc Brown
  • 218,378
Incpetor
  • 127

1 Answers1

5

I'm having a hard time understanding exactly what it is that you're asking but it seems like your question is more to do with removing the usage of an actual HTTP request than anything to do with private methods per se.

Instead of the fetchHTML function being a private function of that object, you should have a separate object that handles HTTP requests. You can then pass a mock version of this object into the constructor of the selector from tests, and this mock can return a fixed value instead of performing an actual HTTP request.