Skip to content

Assert return value of callable throwing exception #1652

Description

@t-8ch

Summary

It would be nice if the assertThatCode().doesNotThrowException() API would be able execute functions that return a value and then return that value for further inspection.
This would make it easy to provide a nice description to an otherwise maybe nondescript exception that is thrown.

Example

@Test 
public void intendedApi() {
  int x = assertThatCode(this::doStuff)
    .describedAs("doing things")
    .doesNotThrowAnyException();
  assertThat(x).isEqualTo(3);
}

@Test
public void currentSolution1() {
  int x;
  try {
    x = doStuff();
  } catch (Exception e) {
    fail("doing things");
    return; // never reached; needed because fail() is not recognized by the java compiler as method exit
  }
  assertThat(x).isEqualTo(3);
}

@Test
public void currentSolution2() {
  AtomicReference<Integer> x = new AtomicReference<>();
  assertThatCode(() -> x.set(doStuff()))
    .describedAs("doing things")
    .doesNotThrowAnyException();
  assertThat(x.get()).isEqualTo(3);
}

// utility for demonstration purposes
public int doStuff() throws Exception {
  if (new Random().nextBoolean()) {
    throw new Exception();
  }
  return 3;
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

No labels
No labels

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions