LoginSignup
0

More than 3 years have passed since last update.

「Factoryクラスでドメインオブジェクトを生成する」という規約をArchUnitでテストする

Last updated at Posted at 2020-12-06

「Factoryメソッドでドメインオブジェクトを生成する」という規約をArchUnitでテストするの続き。

「ドメインオブジェクトの生成を責務とするFactoryクラスが存在するかどうか」テストしてみる。

テスト対象のイメージ


public class Hoge {
    Hoge() {} 
}

public class HogeFactory {
    public Hoge create() {
        return new Hoge();
    }
}

テストコード


@AnalyzeClasses(packages = "com.example")
public class DomainObjectTest {

    @ArchTest
    static ArchRule domain_object_has_no_public_constructors =
        constructors()
            .that().areDeclaredInClassesThat().haveSimpleName("Hoge")
            .should().bePackagePrivate();

    // FactoryクラスにHogeを返すcreateというメソッドが存在すること
    @ArchTest
    static ArchRule factory_class_exists =
        methods().that().areDeclaredInClassesThat().haveSimpleName("HogeFactory")
            .should().haveName("create")
            .andShould().haveRawReturnType("Hoge");
}

FactoryクラスからHogeコンストラクタを呼ぶため、コンストラクタがパッケージプライベートであることをテストしている。

前回のFactoryメソッドのテストの場合はbePrivate()を使用していたが、今回は、同じくArchUnitに用意されているbePackagePrivate()を使用してテストした。

このあたりの基本的なアサーションは一通り利用できるほか、それらを組み合わせて新たな判定ロジックを定義することもArchUnitでは宣言的に実施できる。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0