-3

I'm experimenting with JUnit test, but I'm not sure how would work with this. I have a class whose method returns a String with the name of such method.

public class Example {
    static void method1() {
        System.out.println("method1");
    }

    public static void main(String[] args) {
        method1();
    }
}

Now, I want to test this class with JUnit assertions, but since there are no variables, I don't know how to test this code.

Could someone tell me the full code for this JUnit test?

Tom
  • 16,842
  • 17
  • 45
  • 54
Mr.Dax
  • 1
  • 1
  • 1
    The answer for this particular code would be to patch the stream and catch the input. But this is probably not your real code and you probably aren't just trying to catch the print stream content. How about showing some real code so you can get a real answer to a real problem. – Paul Samsotha Sep 17 '17 at 12:05

1 Answers1

2

This is difficult to unit test because you have a dependency hard-coded into your object. That dependency is the system output console. Remove that dependency from the object and move it to the application's consuming code:

public class Example {
    static String method1() {
        return "method1";
    }

    public static void main(String[]args) {
        System.out.println(method1());
    }
}

Now you can test the method by simply asserting that the value returned by the method is what you expect.

The goal here is to remove dependencies from your code. Things like system console output will have to be somewhere, but you can isolate them behind mockable interfaces as the code gets more complex. Your business logic, the things you want to unit test, should be free from dependencies.

Michal
  • 148
  • 2
  • 6
David
  • 208,112
  • 36
  • 198
  • 279
  • Ok. I understand that the problem is in my original code, so let's simplify it. I have a class with only one method, and this method should return a String type with the name of such method. How would you code it as an alternative to my original code, and so I could make a simple JUnit test on that class? Please could you provide me an example with the full code of that class? Thanks. – Mr.Dax Sep 17 '17 at 12:35
  • @Mr.Dax: So you're just asking how to write a JUnit test at all? There are a variety of examples and tutorials available online. All the test would do in this case is invoke the method and compare the result with an expected result. – David Sep 17 '17 at 12:36