简体   繁体   English

对象创建模拟模型

[英]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. 或者,您创建一个BottomCreator类,在构造时将其传递给Top,并在测试时使用模拟/伪造版本。

public class top {

      private final BottomCreator bottomCreator;

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

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

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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