lundi 28 décembre 2015

Mockito: how to verify method call of a singelton class from another singelton class

I am new to Unit testing and Mockito, how to write test code for given code snippet which is singleton.

1. I want to write unit test for class XYZ
2. I want to verify the whether methods get called or not
3. I want to write test code to check state of temp variable

class ABC is singleton and has two fields num and square.

class ABC{
      private static ABC instance;
      private int num;
      private int square;

      private ABC() {}

      public static ABC getInstance() {
          if (instance == null) {
              instance = new ABC();
          }
          return instance;
      }

      public int getSquar() {
          return square;
      }

      public void setSquar(int square) {
          this.square = square;
      }

      public int getNum() {
          return num;
      }

      public void setNum(int num) {
          this.num = num;
      }
}

class XYZ which is singleton is calling getter and setter from class ABC is also singleton.

class XYZ{
     private static XYZ instance;
     private int temp;

     private XYZ(){}

     public static XYZ getInstance(){
          if (instance == null) {
              instance = new XYZ();
          }
          return instance;
     }

     public void calculateSquare(){
         ABC.getInstance().setNum(5);
         temp = ABC.getInstance().getNum();
         ABC.getInstance().setSquare(temp*temp);

     }  
}

here i am calling calculateSquare method of class XYZ.

XYZ.getInstance().calculateSquare();

Aucun commentaire:

Enregistrer un commentaire