2.13 部分mock

有时候只需要mock部分方法,这时候可以用new Expectations(object),object可以是实例,也可以是class对象。在replay阶段,如果在Expectation中没有进行record,则会调用原有代码。

@Test
public void partiallyMockingASingleInstance() {
  final Collaborator collaborator = new Collaborator(2);

  new Expectations(collaborator) {{
     collaborator.getValue(); result = 123;

     // 静态方法也可以
     Collaborator.doSomething(anyBoolean, "test");
  }};

  // Mocked:
  assertEquals(123, collaborator.getValue());
  Collaborator.doSomething(true, "test");

  // Not mocked:
  assertEquals(45, new Collaborator(45).getValue());
}
  • Note:上面的代码中没有出现@Mocked注解

没有record的方法也可以verify,

@Test
public void partiallyMockingA() {
  final Collaborator collaborator = new Collaborator(123);

  new Expectations(collaborator) {};
  
  int value = collaborator.getValue(); 
  collaborator.simpleOperation(45, "testing", new Date());

  // 没有record也可以verify
  new Verifications() {{ c1.simpleOperation(anyInt, anyString, (Date) any); }};
}

另一种实现部分mock的方法:同时标注@Tested和@Mocked。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • JMockit提供了两套API,一套叫做Expectations,用于基于行为的单元测试;一套叫做Faking,用...
    孙兴斌阅读 1,928评论 0 0
  • 1.Creating mock objects 1.1Class mocks idclassMock=OCMCla...
    奔跑的小小鱼阅读 2,618评论 0 0
  • Martin Fowler的一篇文章。  Key point: two differences; SUT  'M...
    Luna_Lu阅读 1,662评论 0 4
  • Mock 方法是单元测试中常见的一种技术,它的主要作用是模拟一些在应用中不容易构造或者比较复杂的对象,从而把测试与...
    熊熊要更努力阅读 28,401评论 2 25
  • 你我是这世间的两点, 一点是天, 一点是地。 瞭望远方隐约的地平线, 仿佛两点此刻真实的重合在一起, 然而事实却是...
    因往阅读 440评论 1 0