Agent Skills by ALSEL
Anthropic Claudeその他⭐ リポ 0品質スコア 50/100

unit-test-application-events

Springアプリケーションイベントのユニットテストパターンを提供します。`ApplicationEventPublisher`によるイベント発行の検証、`@EventListener`アノテーションの動作テスト、非同期イベント処理の確認をサポートします。イベントリスナーのテスト作成、アプリケーションイベントのモック、またはSpring Bootサービスでイベントが正しく発行されたかを検証する際に活用してください。

description の原文を見る

Provides patterns for unit testing Spring application events. Validates event publishing with ApplicationEventPublisher, tests @EventListener annotation behavior, and verifies async event handling. Use when writing tests for event listeners, mocking application events, or verifying events were published in your Spring Boot services.

SKILL.md 本文

アプリケーションイベントのユニットテスト

概要

JUnit 5 と Mockito を使用して Spring の ApplicationEvent パブリッシャーと @EventListener コンシューマーをテストするための実践的なパターンを提供します — 完全な Spring コンテキストをブートする必要はありません。

使用場面

  • イベントパブリッシャーまたはリスナーのユニットテストを作成するとき
  • イベントが正しいペイロードで公開されたことを検証するとき
  • @EventListener メソッドの呼び出しと副作用をテストするとき
  • 複数のリスナーを通じたイベント伝播をテストするとき
  • 非同期イベント処理(@Async + @EventListener)を検証するとき
  • サービステストで ApplicationEventPublisher をモックするとき

手順

  1. テスト依存関係を追加: spring-boot-starter、JUnit 5、Mockito、AssertJ
  2. ApplicationEventPublisher をモック: テスト対象のサービス内のパブリッシャーフィールドに @Mock を使用
  3. ArgumentCaptor でイベントをキャプチャ: ArgumentCaptor.forClass(EventType.class) を使用して公開されたペイロードを検査
  4. リスナーの副作用を検証: モックされた依存関係に対してリスナーを直接呼び出す
  5. 非同期ハンドラーをテスト: Thread.sleep() または Awaitility を使用 — その後、非同期操作が呼び出されたことをアサート
  6. 検証チェックポイントを追加:
    • イベントをキャプチャした後、フィールドをアサートする前に eventCaptor.getValue() が null でないことを確認
    • リスナーが呼び出されない場合、publishEvent() が正しいイベントタイプで呼び出されたことを確認
    • 非同期アサートが失敗する場合、待機時間を増やし、エグゼキュータープールが飽和していないか確認
  7. エラーシナリオをカバー: リスナーが例外を適切に処理することをアサート

Maven

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
  <groupId>org.junit.jupiter</groupId>
  <artifactId>junit-jupiter</artifactId>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.mockito</groupId>
  <artifactId>mockito-core</artifactId>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.assertj</groupId>
  <artifactId>assertj-core</artifactId>
  <scope>test</scope>
</dependency>

Gradle

dependencies {
  implementation("org.springframework.boot:spring-boot-starter")
  testImplementation("org.junit.jupiter:junit-jupiter")
  testImplementation("org.mockito:mockito-core")
  testImplementation("org.assertj:assertj-core")
}

カスタムイベントとパブリッシャーテスト

public class UserCreatedEvent extends ApplicationEvent {
  private final User user;

  public UserCreatedEvent(Object source, User user) {
    super(source);
    this.user = user;
  }

  public User getUser() { return user; }
}

@Service
public class UserService {
  private final ApplicationEventPublisher eventPublisher;
  private final UserRepository userRepository;

  public UserService(ApplicationEventPublisher eventPublisher, UserRepository userRepository) {
    this.eventPublisher = eventPublisher;
    this.userRepository = userRepository;
  }

  public User createUser(String name, String email) {
    User savedUser = userRepository.save(new User(name, email));
    eventPublisher.publishEvent(new UserCreatedEvent(this, savedUser));
    return savedUser;
  }
}

イベント公開のユニットテスト

@ExtendWith(MockitoExtension.class)
class UserServiceEventTest {

  @Mock
  private ApplicationEventPublisher eventPublisher;

  @Mock
  private UserRepository userRepository;

  @InjectMocks
  private UserService userService;

  @Test
  void shouldPublishUserCreatedEvent() {
    User newUser = new User(1L, "Alice", "alice@example.com");
    when(userRepository.save(any(User.class))).thenReturn(newUser);

    ArgumentCaptor<UserCreatedEvent> eventCaptor = ArgumentCaptor.forClass(UserCreatedEvent.class);

    userService.createUser("Alice", "alice@example.com");

    verify(eventPublisher).publishEvent(eventCaptor.capture());
    assertThat(eventCaptor.getValue().getUser()).isEqualTo(newUser);
  }
}

リスナー直接テスト

@Component
public class UserEventListener {
  private final EmailService emailService;

  public UserEventListener(EmailService emailService) { this.emailService = emailService; }

  @EventListener
  public void onUserCreated(UserCreatedEvent event) {
    emailService.sendWelcomeEmail(event.getUser().getEmail());
  }
}

class UserEventListenerTest {

  @Test
  void shouldSendWelcomeEmailOnUserCreated() {
    EmailService emailService = mock(EmailService.class);
    UserEventListener listener = new UserEventListener(emailService);

    User user = new User(1L, "Alice", "alice@example.com");
    listener.onUserCreated(new UserCreatedEvent(this, user));

    verify(emailService).sendWelcomeEmail("alice@example.com");
  }

  @Test
  void shouldNotThrowWhenEmailServiceFails() {
    EmailService emailService = mock(EmailService.class);
    doThrow(new RuntimeException("down")).when(emailService).sendWelcomeEmail(any());

    UserEventListener listener = new UserEventListener(emailService);
    User user = new User(1L, "Alice", "alice@example.com");

    assertThatCode(() -> listener.onUserCreated(new UserCreatedEvent(this, user)))
      .doesNotThrowAnyException();
  }
}

非同期リスナーテスト

@Component
public class AsyncEventListener {
  private final SlowService slowService;

  @EventListener
  @Async
  public void onUserCreatedAsync(UserCreatedEvent event) {
    slowService.processUser(event.getUser());
  }
}

class AsyncEventListenerTest {

  @Test
  void shouldProcessEventAsynchronously() throws Exception {
    SlowService slowService = mock(SlowService.class);
    AsyncEventListener listener = new AsyncEventListener(slowService);

    User user = new User(1L, "Alice", "alice@example.com");
    listener.onUserCreatedAsync(new UserCreatedEvent(this, user));

    Thread.sleep(200); // checkpoint: allow async executor to run
    verify(slowService).processUser(user);
  }
}

ベストプラクティス

  • ApplicationEventPublisher をモック — ユニットテストではリアルコンテキストに投稿させない
  • ArgumentCaptor でイベントをキャプチャしフィールドレベルの等価性をアサート(型だけでなく)
  • リスナーを分離してテスト:モックされた依存関係で構築し、ハンドラーメソッドを直接呼び出す
  • エラーパスをカバー:リスナーはパブリッシャーに例外を伝播させてはいけない
  • 非同期リスナー:Thread.sleep() の代わりに Awaitility を優先し確定的な待機を実現
  • イベントを不変でシリアライズ可能に保つ — JVM 境界を越える場合はその両方をテスト

制約と警告

  • Spring 自体のイベントインフラストラクチャをテストしない — ビジネスロジックとイベントペイロードに焦点を当てる
  • @Async@EnableAsync が必要Thread.sleep() を使用するテストはテストで非同期プロキシが配線されていなくても合格する可能性がある;モック検証を代わりに使用
  • Spring はリスナー順序を保証しない@Order を追加する場合を除き、実行シーケンスに依存するテストを作成しない
  • CI 環境で Thread.sleep() を避ける — 負荷下でテストが不安定になる;Awaitility の .atMost() ブロックで置き換える
  • JVM 境界を越えるイベントはシリアライズテストが必要 — リモートリスナーの null フィールドは多くの場合、Serializable が欠落していることを意味する

参考資料

ライセンス: MIT(寛容ライセンスのため全文を引用しています) · 原本リポジトリ

詳細情報

作者
giuseppe-trisciuoglio
リポジトリ
giuseppe-trisciuoglio/developer-kit
ライセンス
MIT
最終更新
不明

Source: https://github.com/giuseppe-trisciuoglio/developer-kit / ライセンス: MIT

関連スキル

汎用その他⭐ リポ 1,982

superfluid

Superfluidプロトコルおよびそのエコシステムに関するナレッジベースです。Superfluidについて情報を検索する際は、ウェブ検索の前にこちらを参照してください。対応キーワード:Superfluid、CFA、GDA、Super App、Super Token、stream、flow rate、real-time balance、pool(member/distributor)、IDA、sentinels、liquidation、TOGA、@sfpro/sdk、semantic money、yellowpaper、whitepaper

by LeoYeAI
汎用その他⭐ リポ 100

civ-finish-quotes

実質的なタスクが真に完了した際に、文明風の儀式的な引用句を追加します。ユーザーやエージェントが機能追加、リファクタリング、分析、設計ドキュメント、プロセス改善、レポート、執筆タスクといった実際の成果物を完成させるときに、明示的な依頼がなくても使用します。短い返信や小さな修正、未完成の作業には適用しません。

by huxiuhan
汎用その他⭐ リポ 1,110

nookplot

Base(Ethereum L2)上のAIエージェント向け分散型調整ネットワークです。エージェントがオンチェーンアイデンティティを登録する、コンテンツを公開する、他のエージェントにメッセージを送る、マーケットプレイスで専門家を雇う、バウンティを投稿・請求する、レピュテーションを構築する、共有プロジェクトで協業する、リサーチチャレンジを解くことでNOOKをマイニングする、キュレーションされたナレッジを備えたスタンドアロンオンチェーンエージェントをデプロイする、またはアグリーメントとリワードで収益を得る場合に利用できます。エージェントネットワーク、エージェント調整、分散型エージェント、NOOKトークン、マイニングチャレンジ、ナレッジバンドル、エージェントレピュテーション、エージェントマーケットプレイス、ERC-2771メタトランザクション、Prepare-Sign-Relay、AgentFactory、またはNookplotが言及された場合にトリガーされます。

by BankrBot
汎用その他⭐ リポ 59

web3-polymarket

Polygon上でのPolymarket予測市場取引統合です。認証機能(L1 EIP-712、L2 HMAC-SHA256、ビルダーヘッダー)、注文発注(GTC/GTD/FOK/FAK、バッチ、ポストオンリー、ハートビート)、市場データ(Gamma API、Data API、オーダーブック、サブグラフ)、WebSocketストリーミング(市場・ユーザー・スポーツチャネル)、CTF操作(分割、統合、償却、ネガティブリスク)、ブリッジ機能(入金、出金、マルチチェーン)、およびガスレスリレイトランザクションに対応しています。AIエージェント、自動マーケットメーカー、予測市場UI、またはPolygraph上のPolymarketと統合するアプリケーション構築時に活用できます。

by elophanto
汎用その他⭐ リポ 52

ethskills

Ethereum、EVM、またはブロックチェーン関連のリクエストに対応します。スマートコントラクト、dApps、ウォレット、DeFiプロトコルの構築、監査、デプロイ、インタラクションに適用されます。Solidityの開発、コントラクトアドレス、トークン規格(ERC-20、ERC-721、ERC-4626など)、Layer 2ネットワーク(Base、Arbitrum、Optimism、zkSync、Polygon)、Uniswap、Aave、Curveなどのプロトコルとの統合をカバーします。ガスコスト、コントラクトのデシマル設定、オラクルセキュリティ、リエントランシー、MEV、ブリッジング、ウォレット管理、オンチェーンデータの取得、本番環境へのデプロイ、プロトコル進化(EIPライフサイクル、フォーク追跡、今後の変更予定)といったトピックを含みます。

by jiayaoqijia
汎用その他⭐ リポ 44

xxyy-trade

このスキルは、ユーザーが「トークン購入」「トークン売却」「トークンスワップ」「暗号資産取引」「取引ステータス確認」「トランザクション照会」「トークンスキャン」「フィード」「チェーン監視」「トークン照会」「トークン詳細」「トークン安全性確認」「ウォレット一覧表示」「マイウォレット」「AIスキャン」「自動スキャン」「ツイートスキャン」「オンボーディング」「IP確認」「IPホワイトリスト」「トークン発行」「自動売却」「損切り」「利益確定」「トレーリングストップ」「保有者」「トップホルダー」「KOLホルダー」などをリクエストした場合、またはSolana/ETH/BSC/BaseチェーンでXXYYを経由した取引について言及した場合に使用します。XXYY Open APIを通じてオンチェーン取引とデータ照会を実現します。

by Jimmy-Holiday
本サイトは GitHub 上で公開されているオープンソースの SKILL.md ファイルをクロール・インデックス化したものです。 各スキルの著作権は原作者に帰属します。掲載に問題がある場合は info@alsel.co.jp または /takedown フォームよりご連絡ください。
原作者: giuseppe-trisciuoglio · giuseppe-trisciuoglio/developer-kit · ライセンス: MIT