You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

63 lines
2.2 KiB

  1. using System.Linq;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. using DotNetCore.CAP.Internal;
  5. using DotNetCore.CAP.Test.Helpers;
  6. using Microsoft.Extensions.DependencyInjection;
  7. using Microsoft.Extensions.Logging;
  8. using Xunit;
  9. using Xunit.Abstractions;
  10. namespace DotNetCore.CAP.Test.IntegrationTests
  11. {
  12. public class CancellationTokenSubscriberTest : IntegrationTestBase
  13. {
  14. public CancellationTokenSubscriberTest(ITestOutputHelper testOutput)
  15. : base(testOutput)
  16. {
  17. }
  18. [Fact]
  19. public async Task Execute()
  20. {
  21. await Publisher.PublishAsync(nameof(CancellationTokenSubscriberTest), "Test Message");
  22. await HandledMessages.WaitOneMessage(CancellationToken);
  23. // Explicitly stop Bootstrapper to prove the cancellation token works.
  24. var bootstrapper = Container.GetRequiredService<Bootstrapper>();
  25. await bootstrapper.StopAsync(CancellationToken.None);
  26. var (message, token) = HandledMessages
  27. .OfType<(string Message, CancellationToken Token)>()
  28. .Single();
  29. Assert.Equal("Test Message", message);
  30. Assert.True(token.IsCancellationRequested);
  31. }
  32. protected override void ConfigureServices(IServiceCollection services)
  33. {
  34. services.AddTransient<TestEventSubscriber>();
  35. }
  36. private class TestEventSubscriber : ICapSubscribe
  37. {
  38. private readonly TestMessageCollector _collector;
  39. private readonly ILogger<TestEventSubscriber> _logger;
  40. public TestEventSubscriber(ILogger<TestEventSubscriber> logger, TestMessageCollector collector)
  41. {
  42. _logger = logger;
  43. _collector = collector;
  44. }
  45. [CapSubscribe(nameof(CancellationTokenSubscriberTest),
  46. Group = TestServiceCollectionExtensions.TestGroupName)]
  47. public void Handle(string message, CancellationToken cancellationToken)
  48. {
  49. _logger.LogWarning($"{nameof(Handle)} method called. {message}");
  50. _collector.Add((message, cancellationToken));
  51. }
  52. }
  53. }
  54. }