简体   繁体   中英

Object creation mocking mockito

i have a class top and bottom. i want to unit test the atom class which create the object of bottom.

public class top {

  publiv top() {
     bottom b = new bottom("value");
  }
}

Unit test class:

public class topTest {
   @Test
   public void test(){ 
     top a = new top();
   }
}

while creating a object for top class in test, it will create a object for bottom class.

Here, i want to mock the bottom class object creation. Could anyone help me out on this.

For doing so you should consider to pass the bottom object as parameter. It is always a good practise to pass objects as parameters when an objects are depending on that object.

public class Top {
   private Bottom bottom;

   public Top(Bottom bottom) {
      this.bottom = bottom
   }
}

public class TopTest {
   @Test
   public void test(){ 
      Bottom bottom = mock(Bottom.class);
      Top top = new Top(bottom);
   }
}

You will need to move the logic creating the instance of bottom somewhere. Either in an overrideable method like:

public class top {

  public top() {
     bottom b = new bottom("value");
  }

  protected bottom createBottom() {
     return new bottom("value");
  }
}

And then you can override it in the test:

public class topTest {
   @Test
   public void test(){ 
     top a = new top() {
            protected bottom createBottom() {
               return Mockito.mock(bottom.class);
             }   
             };
   }
}

Or you create a BottomCreator class pass it to Top in construction time and use a mocked/fake version when you test it.

public class top {

      private final BottomCreator bottomCreator;

      public top(BottomCreator creator) {
           this.bottomCreator = creator;
      }

      public top() {
         bottom b = bottomCreator.newBottom();
      }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM