0

I have a utility class that I need to do some unit testing, but within this utility class I have methods that depend on others in that same utility class.

For that I'm using the following dependencies:

  • jUnit:4.12
  • Mockito: 2.8
  • Powermock: 1.7

As it's already evident that I am using Java to perform my code.

Now go to the example code:

public final class AppUtils {

    private AppUtils () {
        throw new UnsupportedOperationException("This class is not instantiable.");
    }

    public static int plus(int a, int b) {
        return a + b;
    }

    public static float average(int a, int b) {
        return ((float) AppUtils.plus(a, b)) / 2;
    }
}

And the unit test:

@RunWith(PowerMockRunner.class)
@PrepareForTest({AppUtils.class})
public class AppUtilsTest {

    @Test
    public void testPlus() { //This test must be good.
        assertEquals(6, AppUtils.plus(4, 2));
    }

    @Test
    public void testAverage() {
        PowerMockito.mockStatic(AppUtils.classs);
        when(AppUtils.plus(anyInt())).thenReturn(6);
        assertEquals(3f, AppUtils.average(4, 3), 1e-2d);
    }

}

That way I did my unit test, but this throws me an error because it tells me that the expected result does not correspond to the actual one.

expected: 3.000f
actual: 0

This is because PowerMock by using the mockStatic() method replaces all static implementations for your defines, but if you do not define the result of one static method then it returns 0.

If anyone can help me, I thank you.

  • Yeah, I need use **easymock** – Gustavo Pacheco Jul 21 '17 at 02:40
  • Simple: dont do that. Timothy is **spot** on. When you have static methods that **break** when they get called during unit testing - then make sure those methods dont break. Follow the advise by Tim and make that stuff not-static for example. – GhostCat Jul 21 '17 at 07:50

1 Answers1

1

UnitTests verify the public observable behavior of the code under test.

The public observable behavior of the CUT includes the return values and the communication with its dependencies.

This means that you treat that other methods as if they where private, just looking at the outcome of the method called.


BTW:

There is no such rule that "utility classes" (in the sense that they provide basic or common functionality) must have static methods only. That's just a common misconception driven by the habit to name classes with only static methods "utility classes".

It is absolutely OK to make all your utility methods non static and instantiate the class before using it.

Dependency Injection (and not the Singelton Pattern) will help you to have only one instance used all around your program...

Community
  • 1
  • 1
Timothy Truckle
  • 15,071
  • 2
  • 27
  • 51