如何在AssertJ的JUnitSoftAssertions规则中集成Guava断言?
Great question! Your understanding is totally correct—out of the box, JUnitSoftAssertions only registers AssertJ's core assertions, not extension modules like the Guava-specific ones. That’s why you’re stuck relying on static imports right now. But there’s a clean fix that lets you keep using that nice fluent, chained syntax you love for Guava types too.
Option 1: Create a reusable custom soft assertions rule (recommended)
The best approach is to extend JUnitSoftAssertions and register the Guava assertion extension in the constructor. This way, you can reuse this custom rule across all tests that need Guava assertions.
First, make the custom class:
import org.assertj.core.api.JUnitSoftAssertions; import org.assertj.guava.api.GuavaAssertions; public class GuavaEnabledSoftAssertions extends JUnitSoftAssertions { public GuavaEnabledSoftAssertions() { // Register the Guava assertion extension with the soft rule register(GuavaAssertions.instance()); } }
Then swap out the standard rule in your test class:
import org.junit.Rule; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; public class YourGuavaTest { @Rule public GuavaEnabledSoftAssertions softy = new GuavaEnabledSoftAssertions(); @Test public void testMultimapContents() { Multimap<String, String> sampleMultimap = ArrayListMultimap.create(); sampleMultimap.put("fruit", "apple"); sampleMultimap.put("fruit", "banana"); // Now you can chain Guava assertions directly on your softy instance! softy.assertThat(sampleMultimap) .containsEntry("fruit", "apple") .hasSize(2) .doesNotContainEntry("fruit", "orange"); } }
Option 2: Manual registration for one-off tests (less ideal)
If you don’t want to create a custom class, you can register the Guava extension directly in individual test methods. This works but is more repetitive:
@Test public void testSingleGuavaAssertion() { // Register the extension before using Guava assertions softy.register(GuavaAssertions.instance()); com.google.common.collect.Multiset<String> sampleMultiset = com.google.common.collect.HashMultiset.create(); sampleMultiset.add("book", 3); softy.assertThat(sampleMultiset) .containsExactly("book", "book", "book") .hasSize(3); }
Quick dependency check
Just to confirm, make sure you have the AssertJ Guava dependency properly added to your build. For Maven, it should look like this (match the version to your core AssertJ version):
<dependency> <groupId>org.assertj</groupId> <artifactId>assertj-guava</artifactId> <version>3.24.2</version> <!-- Use the same version as your assertj-core --> <scope>test</scope> </dependency>
With the custom rule approach, you’ll get all the fluent, chained Guava assertions through your soft rule instance, no more cluttering up your imports with static Guava assertion methods.
内容的提问来源于stack exchange,提问作者JeanValjean

