Hystrix icon indicating copy to clipboard operation
Hystrix copied to clipboard

Javanica: How to test async @HystrixCommand annotated methods?

Open mcbain opened this issue 11 years ago • 3 comments

When not using the annotaions testing async method is documented. https://github.com/Netflix/Hystrix/wiki/How-To-Use#asynchronous-execution

How to test such a method? One would expect to use Future.get() method, but it throws an exception.

@HystrixCommand
    public Future<User> getUserByIdAsync(final String id) {
        return new AsyncResult<User>() {
            @Override
            public User invoke() {
                return userResource.getUserById(id);
            }
        };
    }

The only - hack - is to return the AsyncResult and call AsyncResult.invoke directly, which gets even worse when try to mock such a method call.

mcbain avatar Jun 04 '15 09:06 mcbain

IMHO this is related to https://github.com/Netflix/Hystrix/issues/729 - why force to use the AsyncResult class instead of any Future

mcbain avatar Jun 04 '15 09:06 mcbain

OK, i found a better solution usable in tests.

public class HystrixAsync {
  public static <T> T resolve(Future<T> future) {
    return ((AsyncResult<T>) future).invoke();
  }
}

Testing real command.

@Test
assertThat( HystrixAsync.resolve(abc.getUserByIdAsync("abc")), is(xxx));

Mocking command.

when(abc.getUserByIdAsync).thenReturn(CompletableFuture.completedFuture(value));

mcbain avatar Jun 04 '15 12:06 mcbain

@HystrixCommand public Future getUserByIdAsync(final String id) { return new AsyncResult() { xyz = userResource.getUserById(id) @Override public User invoke() { return xyz; } }; } Can we do something like above? that is fetching the result outside invoke and just do the return inside invoke()? @mcbain @pablete

CoolSuplex avatar Aug 27 '18 20:08 CoolSuplex