Last active
August 29, 2015 14:24
-
-
Save kostapc/386d5eae540bbbc45dab to your computer and use it in GitHub Desktop.
mock async call
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package net.c0f3.random.tests; | |
import org.junit.Test; | |
import org.mockito.invocation.InvocationOnMock; | |
import org.mockito.stubbing.Answer; | |
import java.util.concurrent.atomic.AtomicInteger; | |
import static org.mockito.Mockito.*; | |
/** | |
* Created by KostaPC on 7/4/2015. | |
*/ | |
public class MockitoTests { | |
@Test | |
public void someTest1() { | |
TestService s = new TestService(); | |
TestService spy = spy(s); | |
TestPacket p = new TestPacket(); | |
p.setValue("original"); | |
doAnswer(new Answer() { | |
@Override | |
public Object answer(InvocationOnMock invoc) throws Throwable { | |
final TestPacket tp = (TestPacket) invoc.getArguments()[0]; | |
//System.out.println("hoooked: " + tp); | |
final TestService spy = (TestService) invoc.getMock(); | |
tp.setValue("rewrited"); | |
new Thread(new Runnable() { | |
@Override | |
public void run() { | |
spy.event(tp); | |
} | |
}).start(); | |
return null; | |
} | |
}).when(spy).out(any(TestPacket.class)); | |
spy.out(p); | |
spy.other(); | |
} | |
public class TestService { | |
public void out(TestPacket packet) { | |
System.out.println("out packet! "+packet); | |
} | |
public void event(TestPacket packet) { | |
System.out.println("event packet! "+packet); | |
} | |
public void other() { | |
System.out.println("other method"); | |
} | |
} | |
private static final AtomicInteger count = new AtomicInteger(0); | |
public class TestPacket { | |
private String id; | |
private String value; | |
public TestPacket() { | |
id = String.valueOf(count.incrementAndGet()); | |
} | |
public String getValue() { | |
return value; | |
} | |
public void setValue(String value) { | |
this.value = value; | |
} | |
@Override | |
public String toString() { | |
return id+":"+value; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment