Question

I have a class :

class Abc
{
    public static int fun() {
           // some stuff
           return 5;
    }
}

I have another class:

class Pqr 
{
     public int funToTest() {
            return Abc.fun();

     }
}

I am testing this as follows using mockito:

class PqrTest {
    public int testFunToTest() {
          Abc ob = Mockito.mock(Abc.class);
          Mockito.when(ob.fun()).thenReturn(12);   
    }
}

Now testing like this works fine. But since fun() is a static method, i don't think it should be called via an object. How can i return 12, without calling fun() method's actual implementation using mockito. Also i don't want to call fun() by a mock object of Abc class , as i have done above.

Was it helpful?

Solution

What you want to achieve is possible using tools like PowerMock.

At the same time, you should be aware that there is code which simply is "wrong" when you look at it from a testing perspective. If that's the case, then the correct approach is to change the code until it's easy test. Most of the time, you'll find that the code becomes "better" by this change: Less buggy, easier to understand & maintain, easier to use.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top