JUnit : How to Mock Static Method

Hi,
I was using EasyMock to write Junit for the methods of the class.
The Limitation of this library is that only Interfaces can be mocked without any much effort and behavior can be set according to our needs.
Since, now we need to mock even normal classes, I got mocuer library from net and this too is easy to implement. The problem / limitation is that, I cant mock static methods of a class.
Is there is any workaround / library so that even static methods can be mocked??.
Advance thanks.

Since you would like to mock the static method, it is not part of the class you'd like to test, I assume. The class you do want to test is supposedly under your control and contains the static invocation. I'd suggest to refactor the use of the static invocation in the class being tested.
I see two approaches:
1. wrap the static method call in an instance of newly created service class.
   public class ServiceMethodWrapperImpl implements ServiceMethodWrapper {
       public int serviceCall(String arg) {
         return OtherClass.staticMethod(arg);
   }and then mock the ServiceMethoWrapper interface for testing
2. wrap the static call in a protected method of the class under test. In you test case, test a derived class in which you override the method that calls the service to use a mock:
   public class TestedClass {
     protected int callStaticMethod(String arg) {
         return OtherClass.staticMethod(arg);
     public void something() {
         // replaced OtherClass.staticMethod by
         if (callStaticMethod("Sun") == 3) {
   public void testSomethingForTheClass() {
      TestedClass instance = new TestedClass() {
           protected int callStaticMethod(String arg) {
                return 3; // mocked answer
   }

Similar Messages

  • JUNIT : how to call static methods through mock objects.

    Hi,
    I am writing unit test cases for an action class. The method which i want to test calls one static method of a helper class. Though I create mock of that helper class, but I am not able to call the static methods through the mock object as the methods are static. So the control of my test case goes to that static method and again that static method calls two or more different static methods. So by this I am testing the entire flow instead of testing the unit of code of the action class. So it can't be called as unit test ?
    Can any one suggest me that how can I call static methods through mock objects.

    The OP's problem is that the object under test calls a static method of a helper class, for which he wants to provide a mock class
    Hence, he must break the code under test to call the mock class instead of the regular helper class (because static methods are not polymorphic)
    that wouldn't have happened if this helper class had been coded to interfaces rather than static methods
    instead of :
    public class Helper() {
        public static void getSomeHelp();
    public class MockHelper() {
        public static void getSomeHelp();
    }do :
    public class ClassUnderTest {
        private Helper helper;
        public void methodUnderTest() {  // unchanged
            helper.getSomeHelp();
    public interface Helper {
        public void getSomeHelp();
    public class HelperImpl implements Helper {
        public void getSomeHelp() {
            // actual implementation
    public class MockHelper implements Helper {
        public void getSomeHelp() {
            // mock implementation
    }

  • Reflection: how to call static method?

    You can call an instance method for an object via
    Method method = myClass.getDeclaredMethod(mName, mTypes);
    Object value = method.invoke(instance, mValues);But how do you call a static method (that is perhaps in an abstract class)? Is it save to have the instance variable null?

    Is it save [sic] to have the instance variablenull?Please refrain to mock at that, Peter. Even the
    English often confuse "loose" and "lose", don't be
    that critical to foreigners. :-)Is there something wrong? I just serach via google:
    "is it save to" ... results: 800 ...
    Okay, "is it safe to" : 636.000 ... :-)

  • What is static method

    I can not understand how to use static method
    What is the difference between
    int a;
    static int a;
    what is the meaning of static??

    I would add that a static member exists for the class independently of any instances of the class.
    This means that you can refer to it at any time by using TheClass.theMember.
    This applies to the methods too, like TheClass.theMethod().

  • How to call a static method from an event handler

    Hi,
       I'm trying to call a static method of class I designed.  But I don't know how to do it.  This method will be called from an event handler of a web dynpro for Abap application.
    Can somebody help me?
    Thx in advance.
    Hamza.

    To clearly specify the problem.
    I have a big part code that I use many times in my applications. So I decided to put it in a static method to reuse the code.  but my method calls functions module of HR module.  but just after the declaration ( at the first line of the call function) it thows an exception.  So I can't call my method.

  • How to call a static method in a class if I have just the object?

    Hello. I have an abstract class A where I have a static method blah(). I have 2 classes that extend class A called B and C. In both classes I override method blah(). I have an array with objects of type B and C.
    For every instance object of the array, I'm trying to call the static method in the corresponding class. For objects of type B I want to call blah() method in B class and for objects of type C I want to call blah() method in C class. I know it's possible to call a static method with the name of the object, too, but for some reason (?) it calls blah() method in class A if I try this.
    So my question is: how do I code this? I guess I need to cast to the class name and then call the method with the class name, but I couldn't do it. I tried to use getClass() method to get the class name and it works, but I didn't know what to do from here...
    So any help would be appreciated. Thank you.

    As somebody already said, to get the behavior you
    want, make the methods non-static.You all asked me why I need that method to be
    static... I'm not surprised to hear this question
    because I asked all my friends before posting here,
    and all of them asked me this... It's because some
    complicated reasons, I doubt it.
    the application I'm writing is
    quite big...Irrelevant.
    Umm... So what you're saying is there is no way to do
    this with that method being static? The behavior you describe cannot be obtained with only static methods in Java. You'd have to explicitly determine the class and then explicitly call the correct class' method.

  • How to get the class name  static method which exists in the parent class

    Hi,
    How to know the name of the class or reference to instance of the class with in the main/static method
    in the below example
    class AbstA
    public static void main(String[] args)
    System.out.println(getXXClass().getName());
    public class A extends AbstA
    public class B extends AbstA
    on compile all the class and run of
    java A
    should print A as the name
    java B
    should print B as the name
    Are there any suggestions to know the class name in the static method, which is in the parent class.
    Regards,
    Raja Nagendra Kumar

    Well, there's a hack you can use, but if you think you need it,Could you let me the hack solution for this..
    you probably have a design flaw and/or a misunderstanding about how to use Java.)May be, but my needs seems to be very genuine..of not repeat the main method contents in every inherited class..
    The need we have is this
    I have the test cases inheriting from common base class.
    When the main method of the test class is run, it is supposed to find all other test cases, which belong to same package and subpackages and create a entire suite and run the entire suite.
    In the above need of the logic we wrote in the main method could handle any class provided it knows what is the child class from which this main is called.
    I applicate your inputs on a better way to design without replicating the code..
    In my view getClass() should have been static as the instance it returns is one for all its instances of that class.
    I know there are complications the way compiler handles static vars and methods.. May be there is a need for OO principals to advance..
    Regards,
    Raja Nagendra Kumar
    Edited by: rajanag on Jul 26, 2009 6:03 PM

  • Is there a tutorial on - how to call static java methods

    I have defined external JAVA resource using a .jar file and have successfully catalogged the same. Now I need to pass variables to a static method in a class and also get the return variable mapped into a BPM variable.
    Can someone share sample Java Invokation code, how to call methods in a class, how to instantiate a singleton or reference an existing instance of singleton class.
    Any sample code or sample projects will be useful.
    Also can I se ethe java system.out.println output in BPM Logviewer
    Arvind

    Hi Arvind,
    Sure you've done this, but the first step is to catalog the Jar file. Before an Oracle BPM project can use the Java component, the appropriate Java JAR files must be added to the project.
    Add the Jar File(s) to the External Resources:
    1. Right-click the External Resources item in the Project Navigator tab
    2. From the pop-up menu, select New External Resource.
    3. Name this new Java resource "MyNewJavaComponents" and ensure its type is Java Class Library.
    4. Add the Java jar file(s)
    Catalog and Expose the Java Components:
    5. Add a new module in the Catalog called "IntegrationComponents".
    6. Generate a Java integration component by right-clicking the IntegrationComponents module and select "Catalogue Component" -> "Java".
    7. Using the Java configuration you just created called MyNewJavaComponents, click the Next button to automatically introspect the Java libraries.
    8. Select the class where your method(s) are located and click the Next -> Finish buttons to have Oracle BPM generate the integration component for you.
    9. If you expand the newly exposed Java component, you can see a method has been created for each public method (attributes would also be automatically created if this class had any public attributes). If you've included the appropriate BeanInfo class in the JAR, you'll note that the method parameters are appropriately named.
    How to Invoke Public Java methods Exposed in the Catalog:
    10. Open the method editor for an automatic activity in the process (or any BPM Object method with its "Server Side" property set to "Yes").
    11. Drag one of the Java methods you just exposed inside your IntegrationComponents module into the automatic activity's method. Once you drag it in, here's what you might see if you're using the Java syntax in Oracle BPM's method editor:
    (PdfGenerator).generate(outputFilename : "", contents : {  }, logoImageURL : null, signatureImageURL : null);
    Assuming you have "outputFilename", "sampleContent", "logoURL" and "signatureURL" variables already created in your process, change the method you just dragged in to:
    IntegrationComponents.Pdfservice.PdfGenerator.generate(outputFilename : outputFilename, contents : sampleContent,
    logoImageURL : logoURL, signatureImageURL : signatureURL);
    Hope this helps,
    Dan

  • How do I identify which is static and which is non static method?

    I have a question which is how can i justify which is static and which is non static method in a program? I need to explain why ? I think it the version 2 which is static. I can only said that it using using a reference. But am I correct or ?? Please advise....
    if I have the following :
    class Square
    private double side;
    public Square(double side)
    { this.side = side;
    public double findAreaVersion1()
    { return side * side;
    public double findAreaVersion2(Square sq)
    { return sq.side * sq.side;
    public void setSide(double s)
    { side = s;
    public double getSide()
    { return side;
    } //class Square
    Message was edited by:
    SummerCool

    I have a question which is how can i justify which is
    static and which is non static method in a program? I
    need to explain why ? I think it the version 2 which
    is static. I can only said that it using using a
    reference. But am I correct or ?? Please advise....If I am reading this correctly, that you think that your version 2 is a static method, then you are wrong and need to review your java textbook on static vs non-static functions and variables.

  • How to find the arguments of a static method from the class file

    Hi,all !
    How to find the arguments of a static method from the class file? for example, when we meet a bytecode "invokestatic", how can I know the arguments of this static method?

    Hi,all !
    How to find the arguments of a static method from the
    class file? for example, when we meet a bytecode
    "invokestatic", how can I know the arguments of this
    static method?You mean
    1. The values?
    2. Argument names?
    3. Argument signatures.
    I would suppose for the last that the easiest way would be to parse the signature string.
    The first is not possible - not from the class file.
    The second is only in the debug information stored in the optional part of the class file. And figuring out the format for that is going to be a problem.

  • How to execute a static method twice

    Hi all,
    In the attached code, as you can see I call the method at.sendRequestString(), twice from main() method.
    The first line in sendRequestString() method is Authenticator.setDefault(new MyAuthenticator());
    Authenticator is an abstract class and setDefault is a static method in that class.
    When I call sendRequestString() for the second time, Authenticator.setDefault(new MyAuthenticator()); is not executed. ie; Authenticator.setDefault gets executed once and only once.
    Does this happen because that Authenticator.setDefault is a static method and it will be executed only once?
    If yes, how can I make it work for the second time?
    Here is my simple Java code. The username and password given in the code are just sample ones.
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.Authenticator;
    import java.net.MalformedURLException;
    import java.net.PasswordAuthentication;
    import java.net.URL;
    public class GetAuthenticatedData
         public String address;
         static String username;
         static String password;
         public GetAuthenticatedData(String address){
              this.address = address;
         public String sendRequestString()
              Authenticator.setDefault(new MyAuthenticator());//BEING STATIC METHOD, SET DEFAULT CALLED ONLY ONCE
             String str = null;
             try {
                 URL url = new URL(address);
                 BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
                 while (( str = in.readLine()) != null) {
                      return str;
                 in.close();
             } catch (MalformedURLException e) {
                  System.out.println("e1"+e);
             } catch (IOException e) {
                  System.out.println("e2"+e);
             Authenticator.setDefault(null);
              return str;
         public static void main(String args[]){
              username = "username1";
              password = "password1";
              GetAuthenticatedData at = new GetAuthenticatedData("https://" + username +":"+ password + "@www.mybooo.com/core/Dd002wW.php?data={action:'contacts',args:''}");
              System.out.println("value corresponding to username1 and password1"+at.sendRequestString());
              username = "username2";
              password = "password2";
              at = new GetAuthenticatedData("https://" + username +":"+ password + "@www.mybooo.com/core/Dd002wW.php?data={action:'contacts',args:''}");
              System.out.println("value corresponding to username2 and password2 "+at.sendRequestString());
    class MyAuthenticator extends Authenticator {
         public MyAuthenticator(){
              getPasswordAuthentication();
              protected PasswordAuthentication getPasswordAuthentication() {
                   PasswordAuthentication auth = new PasswordAuthentication(GetAuthenticatedData.username, GetAuthenticatedData.password.toCharArray());
                 System.out.println("Username"+auth.getUserName());
                 System.out.println("Password"+new String(auth.getPassword()));
                   return auth;
    }Please help with an appropriate solution.
    Any help in this regard will be well appreciated with dukes.
    Anees

    Thanks for your valuable help Looce. But it still does not solve the problem.
    Here is how I used your code.
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.Authenticator;
    import java.net.MalformedURLException;
    import java.net.PasswordAuthentication;
    import java.net.URL;
    public class GetAuthenticatedData
         public String address;
         static String username;
         static String password;
         public GetAuthenticatedData(String address){
              this.address = address;
         MyAuthenticator authenticator = new MyAuthenticator("username1","password1".toCharArray());
         public String sendRequestString(String user, String pass)
              authenticator.setUsername(user);
              authenticator.setPassword(pass.toCharArray());
              Authenticator.setDefault(authenticator);
             String str = null;
             try {
                 URL url = new URL(address);
                 BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
                 while (( str = in.readLine()) != null) {
                      return str;
                 in.close();
             } catch (MalformedURLException e) {
                  System.out.println("e1"+e);
             } catch (IOException e) {
                  System.out.println("e2"+e);
             Authenticator.setDefault(null);
              return str;
         public static void main(String args[]){
              username = "username1";
              password = "password1";
              GetAuthenticatedData at = new GetAuthenticatedData("https://" + username +":"+ password + "@www.mybooo.com/core/Dd002wW.php?data={action:'contacts',args:''}");
              System.out.println("value corresponding to username1 and password1"+at.sendRequestString("username1","password1"));
              username = "username2";
              password = "password2";
              at = new GetAuthenticatedData("https://" + username +":"+ password + "@www.mybooo.com/core/Dd002wW.php?data={action:'contacts',args:''}");
              System.out.println("value corresponding to username2 and password2 "+at.sendRequestString("password2","password2"));
    * This class implements an Authenticator whose username and password information can
    * change over time.
    * @author Cynthia G., Sun Java forums: http://forums.sun.com/thread.jspa?messageID=10504183
    class MyAuthenticator extends java.net.Authenticator {
      /** Stored user name. */
      private String username;
      /** Stored password. */
      private char[] password;
      /** Constructs an instance of MyAuthenticator with the given initial user name
       * and password. These may be modified with the setUsername and setPassword
       * methods.
      public MyAuthenticator(String username, char[] password) {
        this.username = username;
        this.password = password;
      public void setUsername(String username) { this.username = username; }
      public void setPassword(char[] password) { this.password = password; }
      protected java.net.PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); }
    }

  • How to use Action listener from Static method

    Hello,
    I am begginer in Java. I am trying to add JButton and add ActionListener to it in the Java tutorial example (TopLevelDemo).
    The problem i am facing are:
    1. Since "private static void createAndShowGUI" method is static I cannot reference (this) in the method addActionLisetener when trying to add the JButton
    JButton pr = new JButton("Print Report");
         pr.addActionListener(this);
    2. If I make "private static void createAndShowGUI" a non static method then it does not run from main method giving me the error(cannot reference non-static).
    3. Where do I put actionPerformed method?
    I did not post the errors for all situations. Just asking how I can Add JButton and add ActionListener to it in the following code
    Thanks
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    /* TopLevelDemo.java requires no other files. */
    public class TopLevelDemo {
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event-dispatching thread.
    private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("TopLevelDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create the menu bar. Make it have a cyan background.
    JMenuBar cyanMenuBar = new JMenuBar();
    cyanMenuBar.setOpaque(true);
    cyanMenuBar.setBackground(Color.cyan);
    cyanMenuBar.setPreferredSize(new Dimension(200, 20));
    //Create a yellow label to put in the content pane.
    JLabel yellowLabel = new JLabel();
    yellowLabel.setOpaque(true);
    yellowLabel.setBackground(Color.yellow);
    yellowLabel.setPreferredSize(new Dimension(200, 180));
    //Set the menu bar and add the label to the content pane.
    frame.setJMenuBar(cyanMenuBar);
    frame.getContentPane().add(yellowLabel, BorderLayout.CENTER);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    }

    Here is one way of doing it...
    JButton btn = new JButton("Click on Me");
    btn.addActionListener(new ActionListener(){
                              public void actionPerformed(ActionEvent ae){
                                // do something
                                }});here we create an anonymous inner class ActionListener and add it to our button...
    - MaxxDmg...
    - ' I am not me... '

  • How to determine the Class of a static methods class?

    hi,
    is there a way to get the code below to output
    foo() called on One.class
    foo() called on Two.classthanks,
    asjf
    public class Two extends One {
       public static void main(String [] arg) {
          One.foo(); // should say "foo() called on One.class"
          Two.foo(); // should say "foo() called on Two.class"
    class One {
       public static final void foo() {
          System.out.println("foo() called on "/*+something.getClass()*/);
    }

    - One.class won't resolve to Two.class when the static
    method is called via the class TwoThat's because static methods are not polymorphic. They cannot be overridden. For example try this:
    public class Two extends One {
       public static void main(String [] arg) {
          One.foo(); // should say "foo() called on One.class"
          Two.foo(); // should say "foo() called on Two.class"
          One one = new Two();
          one.foo();
          ((Two) one).foo();
       public static void foo() {
          System.out.println("foo() called on Two");
    class One {
       public static void foo() {
          System.out.println("foo() called on One");
    }

  • How to get the current class name in static method?

    Hi,
    I'd like to get the current class name in a static method. This class is intended to be extended. So I would expect that the subclass need not to override this method and at the runtime, the method can get the subclass name.
    getClass() doesn't work, because it is not a static method.
    I would suggest Java to make getClass() static. It makes sense.
    But in the mean time, does anybody give an idea to work around it?
    Thank you,
    Bill

    Why not create an instance in a static method and use getClass() of the instance?
    public class Test {
       public static Class getClassName() {
          return new Test().getClass();

  • How are static methods handled in a multithreaded application?

    hi
    i have a class Drawer with a static method public static draw(Graphics g). now assume there are more thrads callin at the same time Drawer.draw(g). What happens? have some threads to wait until the others have finished calling the method, or can static methods be multithreaded, (can they perform simultaniously)?
    thanks, jo

    ups, i am not drawing on the screen, but in every thread i am drawing a Image. this means before i call the static method in every thread there will be created a BufferedImage and then i pass the Graphics from this images to the static method. also in this case the method performs simultaniously? every thread has its own image and graphics, so the static method should be perform at the same time, isn't it?

Maybe you are looking for

  • A serious problem with flush 11.3 on Windows XP! Forgive assistance.../Серьёзная проблема с флешем..

    Я вчера поставил и обнаружил проблему со звуком.(если смотреть видео с звуком(разумеется) или слушать муз через инет(браузер(вообщем где задействован хоть как то  флеф-плеер) звук какой то с разрывами(слушать не возможно).... Это как и в флеше для та

  • Web Dynpro Application Accessing RFC

    Hello, i have some trouble with using RFCs of remote R/3 system. Perhaps anyone can help a poor SAP-rookie. I'd like to execute the tutorial number 4 Web Dynpro Sample Applications and Tutorials. Therefor i installed the "SAP netweaver for java trial

  • Printing the list output.

    Hi All, I want to print the output of the report. I am printing it using NEW-PAGE PRINT ON . and concluded by NEW-PAGE PRINT OFF. I am doing this under the usercommand.  The problem is,, when I say print,(user command), I can print the output but the

  • Leading zeros of matnr.

    i would not like material no to be displayed with leading zeros in my alv report, how to control the dispay patten? "lzero" can only affect numc field.

  • I don't see the album playback time in iTunes 11.

    Hi, I have just downloaded the new version of iTunes and have noticed that it no longer shows album lengths at the bottom of the page as it used to. Is there a way to get this feature back? Thanks