1

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.

Gaurav Kumar
  • 1,091
  • 13
  • 31
  • 2
    If you really want to mock a static method, you could use PowerMock (this extends EasyMock and Mockito). – Chris311 Apr 17 '14 at 13:45

1 Answers1

1

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.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
  • So this means it is not possible to do it using mockito. Okay. Why do u think that this code is wrong wrt testing perspective???. Also can u pls suggest me some good link to study Mockito. – Gaurav Kumar Apr 17 '14 at 17:09
  • A test needs to be able to change everything necessary to simulate the kind of situations that you want to see your code survive. So if you have global variables or functions(`public final static`) and you need to change their behavior during a test, then you should really replace them with something that can be easily exchanged. – Aaron Digulla Apr 18 '14 at 12:49