테스트 추가하기
AbstractAggregateRoot를 이용한 이벤트 처리
트랜잭션을 유발하는 유스케이스
@RequiredArgsConstructor
@Transactional
@Service
public class CreateMember {
private final MemberRepository memberRepository;
public void create(String name) {
Member member = new Member(name);
memberRepository.save(member);
}
}
이벤트를 발생시키는 Entity
@Entity
public class Member extends AbstractAggregateRoot<Member> {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
protected Member() {
}
public Member(String name) {
this.name = name;
registerEvent(new MemberCreatedEvent(name));
}
}
Repository
public interface MemberRepository extends JpaRepository<Member, Long> {
}
이벤트를 처리하는 리스너
@Component
public class MemberCreatedEventListener {
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void handleMemberCreatedEvent(MemberCreatedEvent event) {
System.out.println("event = " + event);
}
}
테스트 클래스
@SpringBootTest
class MemberEventTest {
@Autowired CreateMember createMember;
@MockBean
MemberCreatedEventListener listener;
@Test
void member_created() {
ArgumentCaptor<MemberCreatedEvent> eventCaptor = ArgumentCaptor.forClass(MemberCreatedEvent.class);
createMember.create("msbaek");
verify(listener).handleMemberCreatedEvent(eventCaptor.capture());
Approvals.verify(eventCaptor.getValue().toString());
}
}
Last modified: 31 October 2024