1

I supposed to test a project designed equivalent to something like this :

public class A(){
   public static void init() {
     M.m();
     //some code
   }
}
public class M(){
   public static void m() {
     //some code
   }
}

I need to test the method init() in class A() alone. Therefor I must make a Mock or a stub for M.m() with the same signature of the original one. But without modifying anything in the 2 classes as it's not allowed . How can I make the init() call the stub and ignore the original method in this case where both methods are static ?

Zack Reda
  • 37
  • 5
  • 1
    You cannot Mock or stub a dependency, if it isn't passed into the caller. See https://stackoverflow.com/a/130862/9080015 – curlyBraces Feb 06 '18 at 15:32
  • 1
    @Zack Reda Good question, but it's been asked before. Have you searched through other answers? E.g. [Mocking static methods with Mockito](https://stackoverflow.com/questions/21105403/mocking-static-methods-with-mockito). The most common advice is to avoid static altogether because they are hard to test: [Why Static is Bad and How to Avoid It](https://dzone.com/articles/why-static-bad-and-how-avoid). – Jodiug Feb 06 '18 at 15:36
  • @Jodiug Thanks for the links, Yes I have checked some of them but I don't want to use any Mocking tools and I was waiting for an answer explaining the reflection when it comes to Mocks for Static functions – Zack Reda Feb 06 '18 at 15:46
  • @Zack Reda If I understand correctly, you want to implement the mocking logic yourself. Could you update the question with this requirement, and perhaps a motivation why you can't use existing tools? – Jodiug Feb 07 '18 at 18:25

1 Answers1

1

Static methods cannot be stubbed or mocked without reflection as these are strongly bound to the class definition.

If you can really not change the code, use PowerMock that provides way to mock static methods.
If you can change the code, make this method an instance method and provide a way to set a M dependency in the A class.
So you could stub M.m() very simply.

davidxxx
  • 125,838
  • 23
  • 214
  • 215