検索
ホームページJava&#&チュートリアル猶予付きアサート: AssertJ を使用したよりクリーンなコードのためのカスタム ソフト アサーション

Assert with Grace: Custom Soft Assertions using AssertJ for Cleaner Code

導入

ソフト アサーションが何なのかわからない場合は、「ソフト アサーション – 単体テストと統合テストにソフト アサーションを使用する必要がある理由」をお読みください。

この記事は、Assert J を使用してカスタム アサーションを作成する方法を説明する「Assert with Grace: Custom Assertions for Cleaner Code」の続きです。ここでは、そのアプローチを拡張して、カスタム アサーションに加えてソフト アサーション アプローチを使用する方法を学びます。

AssertJ を使用したカスタム ソフト アサーション

AssertJ の Assertions クラスまたはカスタム クラスを使用して、ハード アサーションを作成できます。ソフト アサーションの利点をすべて得るには、次のことを行う必要があります。

  • カスタム アサーションを実装する
  • カスタム ソフト アサーション クラスを作成し、AssertJ から AbstractSoftAssertion を拡張します

カスタム アサーション

カスタム アサーションの作成方法については、「猶予付きアサート: よりクリーンなコードのためのカスタム アサーション」の記事で学習しました。次のようになります:

public class SimulationAssert extends AbstractAssert<simulationassert simulation> {
    protected SimulationAssert(Simulation actual) {
        super(actual, SimulationAssert.class);
    }
    public static SimulationAssert assertThat(Simulation actual) {
        return new SimulationAssert(actual);
    }
    public SimulationAssert hasValidInstallments() {
        isNotNull();
        if (actual.getInstallments() = 48) {
            failWithMessage("Installments must be must be equal or greater than 2 and equal or less than 48");
        }
        return this;
    }
    public SimulationAssert hasValidAmount() {
        isNotNull();
        var minimum = new BigDecimal("1.000");
        var maximum = new BigDecimal("40.000");
        if (actual.getAmount().compareTo(minimum)  0) {
            failWithMessage("Amount must be equal or greater than $ 1.000 or equal or less than than $ 40.000");
        }
        return this;
    }
}
</simulationassert>

カスタム アサーションを使用すると、テストでの読みやすさが向上するだけでなく、有効な値をテストする責任がカスタム アサーションに送信されます。

class SimulationsCustomAssertionTest {
    @Test
    void simulationErrorAssertion() {
        var simulation = Simulation.builder().name("John").cpf("9582728395").email("john@gmail.com")
                .amount(new BigDecimal("1.500")).installments(5).insurance(false).build();
        SimulationAssert.assertThat(simulation).hasValidInstallments();
        SimulationAssert.assertThat(simulation).hasValidAmount();
    }
}

カスタム アサーションを用意したら、カスタム ソフト アサーションを実装します。

カスタム ソフト アサーションを作成する

カスタム ソフト アサーションを作成する簡単なプロセスがあり、前提条件としてカスタム アサーションを実装する必要があります。前の記事を考慮すると、カスタム アサーションとして SimulationAssert クラスがあり、カスタム ソフト アサーションとして SimulationSoftAssert を作成します。手順は次のとおりです:

  1. AbstractSoftAssertions クラスを拡張します
  2. 次のコマンドを使用して、assertThat() メソッドを作成します。
    • メソッドはカスタム アサーション クラスとしてオブジェクトを返します
    • アサーションの主題へのパラメータ
    • メソッドは、パラメータがカスタム アサーション クラスとアサーションのサブジェクトであるメソッド プロキシを返します
  3. 次のコマンドを使用して、assertSoftly() メソッドを作成します。
    • カスタム ソフト アサート クラスのコンシューマとしてのパラメータ
    • パラメータがカスタム ソフト アサーション クラスとメソッド パラメータであるため、SoftAssertionsProvider.assertSoftly() メソッドを使用します

手順は複雑に見えますが、実際には次のようになります。

public class SimulationSoftAssert extends AbstractSoftAssertions {
    public SimulationAssert assertThat(Simulation actual) {
        return proxy(SimulationAssert.class, Simulation.class, actual);
    }
    public static void assertSoftly(Consumer<simulationsoftassert> softly) {
        SoftAssertionsProvider.assertSoftly(SimulationSoftAssert.class, softly);
    }
}
</simulationsoftassert>

カスタム ソフト アサーションの使用

AssertJ SoftAssertion クラスはソフト アサーションを担当します。これは、シミュレーション コンテキストに適用できる例です:

AssertJ SoftAssertion クラスはソフト アサーションを担当します。これは、シミュレーション コンテキストに適用できる例です:

public class SimulationAssert extends AbstractAssert<simulationassert simulation> {
    protected SimulationAssert(Simulation actual) {
        super(actual, SimulationAssert.class);
    }
    public static SimulationAssert assertThat(Simulation actual) {
        return new SimulationAssert(actual);
    }
    public SimulationAssert hasValidInstallments() {
        isNotNull();
        if (actual.getInstallments() = 48) {
            failWithMessage("Installments must be must be equal or greater than 2 and equal or less than 48");
        }
        return this;
    }
    public SimulationAssert hasValidAmount() {
        isNotNull();
        var minimum = new BigDecimal("1.000");
        var maximum = new BigDecimal("40.000");
        if (actual.getAmount().compareTo(minimum)  0) {
            failWithMessage("Amount must be equal or greater than $ 1.000 or equal or less than than $ 40.000");
        }
        return this;
    }
}
</simulationassert>

これを使用する場合の「問題」は、作成したカスタム アサーションを使用できないことです。上記の例では、SoftAssertions クラスはカスタム アサーションにアクセスできないため、isEqualTo() を使用して分割払いと金額のアサーションを確認できます。

カスタム ソフト アサーション クラスを作成することで、この問題を解決しました。したがって、SoftAssertions クラスを使用する代わりに、カスタム クラス SimulationSoftAssert.
を使用します。

class SimulationsCustomAssertionTest {
    @Test
    void simulationErrorAssertion() {
        var simulation = Simulation.builder().name("John").cpf("9582728395").email("john@gmail.com")
                .amount(new BigDecimal("1.500")).installments(5).insurance(false).build();
        SimulationAssert.assertThat(simulation).hasValidInstallments();
        SimulationAssert.assertThat(simulation).hasValidAmount();
    }
}

SimulationSoftAssert.assertSoftly() は、アサーション中のエラーやその他のアクティビティを管理できるようにすべての内部メソッドを呼び出すソフト アサーションのプロバイダーです。使用中のassertThat()は、assertSoftly()内で、ソフト・アサートとアサーションのサブジェクトの間のproxy()によってカスタム・アサーションにアクセスできるカスタムのものになります。

このアプローチを使用すると、カスタム アサーションを実装することにより、ソフト アサーションでカスタム アサーションを利用できるようになります。

終わり

以上です!

完全に実装され、実際に動作する例は、credit-api プロジェクトにあります。ここでは、次の内容を確認できます。

  • SimulationAssert クラス
  • SimulationsCustomAssertionTest クラスでのテストの使用法

以上が猶予付きアサート: AssertJ を使用したよりクリーンなコードのためのカスタム ソフト アサーションの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
Javaはまだ新機能に基づいた良い言語ですか?Javaはまだ新機能に基づいた良い言語ですか?May 12, 2025 am 12:12 AM

JavaremainsagoodlanguagedueToitscontinuousevolution androbustecosystem.1)lambdaexpressionsenhancecodereadability andenableFunctionalprogramming.2)streamsalowsolowsolfisitydataprocessing、特に特にlagedatasets.3)硬化系系統系系統系系統系系統

何がJavaを素晴らしいものにしますか?主な機能と利点何がJavaを素晴らしいものにしますか?主な機能と利点May 12, 2025 am 12:11 AM

Javaisgreatduetoitsplatformindependence、robustoopsupport、extensiveLibraries、andstrongCommunity.1)PlatformentepenteviajvMallowsCodeTorunonVariousPlatforms.2)oopeatureSlikeEncapsulation、遺伝、およびポリモ系系統型皮下皮質皮下Rich

トップ5のJava機能:例と説明トップ5のJava機能:例と説明May 12, 2025 am 12:09 AM

Javaの5つの主要な特徴は、多型、Lambda Expressions、StreamSapi、ジェネリック、例外処理です。 1。多型により、さまざまなクラスのオブジェクトを一般的なベースクラスのオブジェクトとして使用できます。 2。Lambda式は、コードをより簡潔にし、特にコレクションやストリームの処理に適しています。 3.ストリームサピは、大規模なデータセットを効率的に処理し、宣言操作をサポートします。 4.ジェネリックは、タイプの安全性と再利用性を提供し、型刻印中にタイプエラーがキャッチされます。 5.例外処理は、エラーをエレガントに処理し、信頼できるソフトウェアを作成するのに役立ちます。

Javaのトップ機能は、パフォーマンスとスケーラビリティにどのような影響を与えますか?Javaのトップ機能は、パフォーマンスとスケーラビリティにどのような影響を与えますか?May 12, 2025 am 12:08 AM

java'stoputuressificlynificlytallysperformanceandscalability.1)object-oriented-principleslikepolymorphismenabledscalablecode.2)garbagecolectionAutomateMemorymarymanagemenateButcancausElatenceSuses.3)

JVM Internals:Java Virtual Machineの奥深くに飛び込みますJVM Internals:Java Virtual Machineの奥深くに飛び込みますMay 12, 2025 am 12:07 AM

JVMのコアコンポーネントには、クラスローダー、runtimedataarea、executionEngineが含まれます。 1)クラスローダーは、クラスとインターフェイスの読み込み、リンク、初期化を担当します。 2)runtimedataareaには、Methodarea、Heap、Stack、Pcregister、Nativemethodstackが含まれています。 3)ExecutionEngineは、Bytecodeの実行と最適化を担当する通訳、JitCompiler、GarbageCollectorで構成されています。

Javaを安全で安全にする機能は何ですか?Javaを安全で安全にする機能は何ですか?May 11, 2025 am 12:07 AM

Java'ssafetyandsecurityarebolteredby:1)stronttyping、whathspreventype-relatederrors; 2)自動メモリ管理viagarbagececollection、3)サンドボクシング、分離コードフロムシェシシステム;

必見のJava機能:コーディングスキルを向上させます必見のJava機能:コーディングスキルを向上させますMay 11, 2025 am 12:07 AM

Javaoffersseveralkeyfeaturesthatenhancecodingskills:1)Object-orientedprogramingallowsmodelingreal-worldentities、explifiedBypolymorphism.2)例外ハンドリングプロビッドログスロルマニネーション

JVM最も完全なガイドJVM最も完全なガイドMay 11, 2025 am 12:06 AM

jvmisacrucialcomponentthaturunsjavacodebytrantingintiTomachine特異的インストラクション、パフォーマンス、セキュリティ、およびポータビリティに影響を与えます

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

Dreamweaver Mac版

Dreamweaver Mac版

ビジュアル Web 開発ツール

MantisBT

MantisBT

Mantis は、製品の欠陥追跡を支援するために設計された、導入が簡単な Web ベースの欠陥追跡ツールです。 PHP、MySQL、Web サーバーが必要です。デモおよびホスティング サービスをチェックしてください。

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

SublimeText3 英語版

SublimeText3 英語版

推奨: Win バージョン、コードプロンプトをサポート!