1

I have a simple unit test which asserts on an object instance of Try from the vavr library.

@Test
public void testFoo()
{
    final Try<Foo> result = createMyFooInstance();

    assertThat(result.isSuccess()).isTrue();
}

My question focuses on the formulation of the test assertion. Semantically I want to have "if foo is success, all fine, otherwise, throw the encapsulated exception". The latter one is important so that I can see the error cause directly in the JUnit output.

Is there any convenient API that I can use to nicely formulate that semantics?

Emdee
  • 1,689
  • 5
  • 22
  • 35
  • You have no assertion in that test. You would need `assertThat(result.isSuccess()).isTrue()` to actually have an assertion. Asking for library recommendations is off-topic here. – JB Nizet Mar 18 '19 at 10:00
  • You're right, I overlooked it. I do not get your point about library recommendations. I am asking whether the libraries AssertJ, Vavr and related allow me a nice formulation of the semantics. So I am not asking for a new library, but rather how to use them properly. – Emdee Mar 18 '19 at 10:10

1 Answers1

0

You could use

@Test
public void testFoo() {
    final Try<Foo> result = createMyFooInstance();
    result.get();
}

In case when result is a Failure, result.get() will throw the wrapped exception. In case when result is a Success, it will succeed.

Though this solution doesn't contain explicit assertions, it will implicitly fail the cases when the result is a Failure.

If you prefer to have an assertion failed instead of a test failed with exception, you could also use:

@Test
public void testFoo() {
    final Try<Foo> result = createMyFooInstance();
    assertThatCode(result::get).doesNotThrowAnyException();
}
Nándor Előd Fekete
  • 6,988
  • 1
  • 22
  • 47
  • 1
    How about `assertThat(result.get()).isEqualTo(myExpectation);`? This will both throw if it was a failure, and allows you to assert of the success result. BTW that's what we do in my team. Also, worth mentioning the recent assertj-vavr library, I see cool stuff like `shouldContain()` from https://github.com/assertj/assertj-vavr/blob/master/src/main/java/org/assertj/vavr/api/TryShouldContain.java – Sir4ur0n Mar 22 '19 at 09:50
  • Yes, but according to the question they don't have anything to compare the result to. They just want to know if it's successful, and throw the original exception if not - that's essentially unwrapping the `Try` with `get()`. – Nándor Előd Fekete Mar 22 '19 at 12:55