Junit / Mockito - wait for the method to complete

In my application, I use the observer pattern for some operations, and I want to test them in unit tests. The problem is that I don’t know how I can check observers using junit / mockito / something else. Any help?

For example, this is my unit test:

@Before public void setUp() throws IOException, Exception { observer = new GameInstanceObserver(); // observable (GameInstance) will call update() method after every change GameInstance.getInstance().addObserver(observer); // this is observable which is updated by serverService } @Test(expected = UserDataDoesntExistException.class) public void getRoomUserData_usingNullKey_shouldThrowUserDataDoesntExist() throws InterruptedException, UserDataDoesntExistException { serverService.createRoom("exampleRoom"); // this operation is asynchronous and updates GameInstance data (as I wrote before GameInstance is Observable) Thread.sleep(400); // how to do it in better way? GameInstance gi = (GameInstance) observer.getObservable(); assertTrue(gi.getRoom("exampleRoom").getRoomId().equals("exampleRoom")); } 

I would not want to use Thread.sleep() and use it this way (or similar):

 @Test(expected = UserDataDoesntExistException.class) public void getRoomUserData_usingNullKey_shouldThrowUserDataDoesntExist() throws InterruptedException, UserDataDoesntExistException { serverService.createRoom("exampleRoom"); // this operation is asynchronous and updates GameInstance data (as I wrote before GameInstance is Observable) waitUntilDataChange(GameInstance.getInstance()); // wait until observable will be changed so I know that it notified all observer and I can validate data GameInstance gi = (GameInstance) observer.getObservable(); assertTrue(gi.getRoom("exampleRoom").getRoomId().equals("exampleRoom")); } 
+4
source share
1 answer

If I understand correctly, the problem is not to check the observer, but to check the result of the asynchronous method call. To do this, create an observer that blocks until the update () method is called. Something like the 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 your 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()); } 
+9
source

Source: https://habr.com/ru/post/1481645/


All Articles