I want to execute some code when a particular mock method is invoked.
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");
Is there any approach where I can achieve to perform an Invoke action when a mock is called?
mock.Connected().Invoke () //something like this?
What i have so far is,
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");
Wanted to check if there is a better and clean way.
I found the addDelegate
to solve my problem.. Not so clear and intuitive but slightly better than my previous approach.
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);
}
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.