Lacju
Lacju

Reputation: 91

How can I use an assertion to test this java code?

My homework assignment is to read a URL and print all hyperlinks at that URL to a file. I also need to submit a junit test case with at least one assertion. I have looked at the different forms of Assert but I just can't come up with any use of them that applies to my code. Any help steering me in the right direction would be great.

(I'm not looking for anyone to write the test case for me, just a little guidance on what direction I should be looking in)

public void saveHyperLinkToFile(String url, String fileName)
throws IOException
{

    URL pageLocation = new URL(url);
    Scanner in = new Scanner(pageLocation.openStream());
    PrintWriter out = new PrintWriter(fileName);

    while (in.hasNext())
    {
        String line = in.next();
        if (line.contains("href=\"http://"))
        {
            int from = line.indexOf("\"");
            int to = line.lastIndexOf("\"");
            out.println(line.substring(from + 1, to));

        }


    }
    in.close();
    out.close();

}

}

Upvotes: 0

Views: 129

Answers (1)

lexicore
lexicore

Reputation: 43709

Try to decompose your method into simpler ones:

  • List<URL> readHyperlinksFromUrl(URL url);
  • void writeUrlsToFile(List<URL> urls, String fileName);

You could already test your first method by saving a sample document as a resource and running it against that resource, comparing the result with the known list of URLs.

You can also test the second method by re-reading that file.

But you can decompose things further on:

  • void writeUrlsToWriter(List<URL> urls, Writer writer);
  • Writer createFileWriter(String fileName);

Now you can test your first method by writing to a StringWriter and checking, what was written there by asserting the equality of writer.toString() with the sample value. Not that methods are becoming simpler and simpler.

It would be actually a very good exercise to write the whole thing test-first or even play ping-pong with yourself.

Upvotes: 1

Related Questions