0

I am new to the concept of writing unit tests so I'm not sure how to go on about this. I have the following method in my class which is a class full of helper functions which gets used around my app:

public static float getCurrentTime() {
    Calendar calandar = Calendar.getInstance();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
    String[] time = simpleDateFormat.format(calandar.getTime()).split(":");
    float returnResult = /*perform some calculations*/
    return returnResult ;
}

Now in this method, the result depends on what time it is. In my unit test, I want to control that aspect to ensure to gives me the right time but I'm not sure how to do that. I looked up powermockito and using the when(..).then(..) method, also looked into mocking the calender object but because its instantiated in the method, it doesn't look like that'll work. Any ideas? I have no constructors in this class as all the methods in this class is static so I simply call the methods by class name rather than instantiating an object of this class.

1 Answers1

2

All the problems you mentioned here are because you are using static methods throughout the rest of your code, and those are really hard to mock.

This how your tests are telling you that you should change design.

Instead of having static method, you may have class called TimeProvider, with one method getCurrentTime().

That can be mocked and injected in your tests. All testing in that case will be much easier since you could then use that mock to provide any float you want in tests depending on that method.

  • so is using static methods generally not a good thing because its hard to mock? – dfqupwndguerrillamailde Feb 03 '18 at 10:28
  • @dfqupwndguerrillamailde http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/ – Dawood ibn Kareem Feb 03 '18 at 10:41
  • From my perspective, definitely. Here you have nice article about that: http://blog.christianposta.com/testing/java-static-methods-can-be-a-code-smell/ Perspectives are different though, and some consider static methods good thing to practice. – Mladen Milić Feb 03 '18 at 10:43