Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Provide a variant of assertArg that works well with checked exceptions #2982

Closed
wilkinsona opened this issue Apr 19, 2023 · 2 comments · Fixed by #2991
Closed

Provide a variant of assertArg that works well with checked exceptions #2982

wilkinsona opened this issue Apr 19, 2023 · 2 comments · Fixed by #2991

Comments

@wilkinsona
Copy link

wilkinsona commented Apr 19, 2023

#2949 is a great new feature, thank you. While trying to make use of it in Spring Boot, I came across a situation that would benefit from the consumer of the argument being able to throw checked exceptions:

then(this.client).should().executeOpen(any(HttpHost.class), assertArg((request) -> {
	assertThat(request).isInstanceOf(HttpPost.class);
	assertThat(request.getUri()).isEqualTo(this.uri);
	assertThat(request.getFirstHeader(HttpHeaders.CONTENT_TYPE)).isNull();
	assertThat(request.getFirstHeader(HttpClientTransport.REGISTRY_AUTH_HEADER)).isNull();
	assertThat(response.getContent()).isSameAs(this.content);
}), isNull());

In this example, request is an org.apache.hc.client5.http.classic.methods.HttpPost and getUri() and getContent() throw URISyntaxException and IOException respectively. As a result, the above snippet does not compile.

I can work around this by using AssertJ's ThrowingConsumer:

then(this.client).should().executeOpen(any(HttpHost.class), assertArg((ThrowingConsumer<HttpPost>) (request) -> {
	assertThat(request).isInstanceOf(HttpPost.class);
	assertThat(request.getUri()).isEqualTo(this.uri);
	assertThat(request.getFirstHeader(HttpHeaders.CONTENT_TYPE)).isNull();
	assertThat(request.getFirstHeader(HttpClientTransport.REGISTRY_AUTH_HEADER)).isNull();
	assertThat(response.getContent()).isSameAs(this.content);
}), isNull());

As you can see, it requires a cast which is ever so slightly inelegant. It also won't help a Mockito user who doesn't use AssertJ. Would you consider adding a ThrowingConsumer interface to Mockito along with a variant of assertArg that takes a ThrowingConsumer rather than a Consumer?

@TimvdLippe
Copy link
Contributor

Yes that sounds like a useful alternative API! I am not sure if we need to keep both in Mockito 6, but that we will need to see. Do you mind sending us a PR with the new API and corresponding tests? Thanks!

@nicolas-ot
Copy link
Contributor

I am working on this

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

Successfully merging a pull request may close this issue.

3 participants