Search code examples
javastaticpowermock

can powermock be used to test static methods


I have the following two classes:

public class Prod
{   
    public  void logon(){        
        System.out.println("'\u000CProd  logon");        
        addUser();        
    }
        public  void addUser(){     
        System.out.println("Prod  addUser");
    }
}

public class Dev extends Prod
{
    public void addUser(){     
       System.out.println("Dev  addUser");
    }    
    public static void main(String[] args){         
       Dev test = new Dev(); 
       test.logon(); 
    }   
}

Is there a way to make all the methods static and then test whether the Dev.addUser() is working correctly?

Here's what I would like to be able to do:

public class Prod
{   
    public static void logon(){        
        System.out.println("'\u000CProd  logon");        
        addUser();        
    }
        public static void addUser(){     
        System.out.println("Prod  addUser");
    }
}

public class Dev extends Prod
{
    public static void addUser(){     
       System.out.println("Dev  addUser");
    }    
    public static void main(String[] args){  
       logon(); 
    }   
}

When I run the main() in Dev we should get:

Prod logon

Dev addUser


Solution

  • Is there a way to make all the methods static and then test whether the Dev.addUser() is working correctly?

    No, there isn't.

    This is really fundamental Java: you want to use static methods in a polymorphic context. But static methods are not polymorphic. There is no true inheritance, there is no overwriting of static methods. See here for lengthy explanations why that is. Repeat: the desired output can't be achieved in a purely static way, built around class A extending class B. End of story.

    And as already said: this is also wrong from a conceptual point. Because of such restrictions, static should only be used carefully in Java. Simply go with the non-static code you have right now.

    Unfortunately your question isn't really clear what exactly you intend to test, therefore I can't help with that part.