猿问

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

我想在调用特定的模拟方法时执行一些代码。


mock = EasyMock.createMock(ConListener.class);


// Record n Replay

mock.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 Replay

mock.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");

想检查是否有更好、更干净的方法。


慕田峪4524236
浏览 102回答 1
1回答

繁星coding

我发现addDelegate可以解决我的问题..不是那么清晰和直观,但比我以前的方法稍好一些。interface ConListener {&nbsp; &nbsp;void Connected();&nbsp; &nbsp;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 {&nbsp; &nbsp;void Connected() {Assert.fail("")}&nbsp; &nbsp;void DataSent(int size) {Assert.fail("")}}@Testpublic void SomeTest() {&nbsp; &nbsp;CompletableFuture<Void> connected = new CompletableFuture<Void>();&nbsp; &nbsp;mock = EasyMock.createMock(ConListener.class);&nbsp; &nbsp;// Record&nbsp; &nbsp;mock.Connected();&nbsp; &nbsp;EasyMock.expectLastCall().andDelegateTo(new TestListener() {&nbsp; &nbsp; &nbsp; public void Connected() {&nbsp; &nbsp; &nbsp; &nbsp; connected.complete(null);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;});&nbsp; EasyMock.expectLastCall().times(1); // This cannot come before adding delegates. Why?&nbsp; EasyMock.replay(mock);&nbsp; // Test&nbsp; sock = createCon(addr, mock/*using actual mock*/);&nbsp; connected.get(timeout, unit);&nbsp; sock.send(blahblah);&nbsp;&nbsp;}
随时随地看视频慕课网APP

相关分类

Java
我要回答