java - Junit/Mockito - wait for method execution -
in application use observer pattern operations , want test them in unit tests. problem don't know how can test observers using junit/mockito/something else. help?
for example unit test:
@before public void setup() throws ioexception, exception { observer = new gameinstanceobserver(); // observable (gameinstance) call update() method after every change gameinstance.getinstance().addobserver(observer); // observable updated serverservice } @test(expected = userdatadoesntexistexception.class) public void getroomuserdata_usingnullkey_shouldthrowuserdatadoesntexist() throws interruptedexception, userdatadoesntexistexception { serverservice.createroom("exampleroom"); // operation asynchronous , updates gameinstance data (as wrote before gameinstance observable) thread.sleep(400); // how in better way? gameinstance gi = (gameinstance) observer.getobservable(); asserttrue(gi.getroom("exampleroom").getroomid().equals("exampleroom")); }
i not use thread.sleep()
, use in way (or similar):
@test(expected = userdatadoesntexistexception.class) public void getroomuserdata_usingnullkey_shouldthrowuserdatadoesntexist() throws interruptedexception, userdatadoesntexistexception { serverservice.createroom("exampleroom"); // operation asynchronous , updates gameinstance data (as wrote before gameinstance observable) waituntildatachange(gameinstance.getinstance()); // wait until observable changed know notified observer , can validate data gameinstance gi = (gameinstance) observer.getobservable(); asserttrue(gi.getroom("exampleroom").getroomid().equals("exampleroom")); }
if understand correctly, problem not test observer, test result of asynchronous method call. that, create observer blocks until update() method has been called. following:
public class blockinggameobserver extends gameinstanceobserver { private countdownlatch latch = new countdownlatch(1); @override public void update() { latch.countdown(); } public void waituntilupdateiscalled() throws interruptedexception { latch.await(); } }
and in test:
private blockinggameobserver observer; @before public void setup() throws ioexception, exception { observer = new blockinggameobserver(); gameinstance.getinstance().addobserver(observer); } @test public void getroomuserdata_usingnullkey_shouldthrowuserdatadoesntexist() throws interruptedexception, userdatadoesntexistexception { serverservice.createroom("exampleroom"); observer.waituntilupdateiscalled(); assertequals("exampleroom", gameinstance.getinstance().getroom("exampleroom").getroomid()); }
Comments
Post a Comment