为了账号安全,请及时绑定邮箱和手机立即绑定

java easymock:调用模拟时可以调用另一个方法吗?

java easymock:调用模拟时可以调用另一个方法吗?

慕田峪4524236 2023-07-13 17:51:09
我想在调用特定的模拟方法时执行一些代码。mock = EasyMock.createMock(ConListener.class);// Record n Replaymock.Connected();mock.DataSent();EasyMock.replay(mock);sock = createCon(addr, mock)// I want the send to be called only after the mock's Connected() is invoked.sock.send("data");有没有什么方法可以在调用模拟时执行调用操作?mock.Connected().Invoke () //something like this? 到目前为止我所拥有的是mock = EasyMock.createMock(ConListener.class);// Record n Replaymock.Connected();mock.DataSent();EasyMock.replay(mock);CompletableFuture<Void> connected = new CompletableFuture<Void>();sock = createCon(addr, new ConListener() {   public void Connected() {      mock.Connected();      connected.complete(null);   }   public void DataSent() { mock.DataSent(); }});connected.get()sock.send("data");想检查是否有更好、更干净的方法。
查看完整描述

1 回答

?
繁星coding

TA贡献1797条经验 获得超4个赞

我发现addDelegate可以解决我的问题..不是那么清晰和直观,但比我以前的方法稍好一些。


interface ConListener {

   void Connected();

   void DataSent(int size);

}


// Having it as a class, so that I can only add stub codes,

// for a particular method and leave the rest.


class TestListener implements ConListener {

   void Connected() {Assert.fail("")}

   void DataSent(int size) {Assert.fail("")}

}



@Test

public void SomeTest() {

   CompletableFuture<Void> connected = new CompletableFuture<Void>();

   mock = EasyMock.createMock(ConListener.class);


   // Record

   mock.Connected();

   EasyMock.expectLastCall().andDelegateTo(new TestListener() {

      public void Connected() {

        connected.complete(null);

      }

   });

  EasyMock.expectLastCall().times(1); // This cannot come before adding delegates. Why?

  EasyMock.replay(mock);


  // Test

  sock = createCon(addr, mock/*using actual mock*/);

  connected.get(timeout, unit);

  sock.send(blahblah);  


}



查看完整回答
反对 回复 2023-07-13
  • 1 回答
  • 0 关注
  • 101 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信