Commit d222559c authored by Savorboard's avatar Savorboard

Remove outdated unit tests

parent 82416af8
......@@ -2,8 +2,6 @@
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using DotNetCore.CAP.Abstractions;
using DotNetCore.CAP.Messages;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Xunit;
......@@ -53,29 +51,6 @@ namespace DotNetCore.CAP.Test
Assert.NotNull(thingy);
}
[Fact]
public void CanOverrideContentSerialize()
{
var services = new ServiceCollection();
services.AddCap(x => { }).AddContentSerializer<MyContentSerializer>();
var thingy = services.BuildServiceProvider()
.GetRequiredService<IContentSerializer>() as MyContentSerializer;
Assert.NotNull(thingy);
}
[Fact]
public void CanOverrideMessagePack()
{
var services = new ServiceCollection();
services.AddCap(x => { }).AddMessagePacker<MyMessagePacker>();
var thingy = services.BuildServiceProvider()
.GetRequiredService<IMessagePacker>() as MyMessagePacker;
Assert.NotNull(thingy);
}
[Fact]
public void CanResolveCapOptions()
......@@ -87,38 +62,6 @@ namespace DotNetCore.CAP.Test
Assert.NotNull(capOptions);
}
private class MyMessagePacker : IMessagePacker
{
public string Pack(CapMessage obj)
{
throw new NotImplementedException();
}
public CapMessage UnPack(string packingMessage)
{
throw new NotImplementedException();
}
}
private class MyContentSerializer : IContentSerializer
{
public T DeSerialize<T>(string content)
{
throw new NotImplementedException();
}
public object DeSerialize(string content, Type type)
{
throw new NotImplementedException();
}
public string Serialize<T>(T obj)
{
throw new NotImplementedException();
}
}
private class MyProducerService : ICapPublisher
{
public IServiceProvider ServiceProvider { get; }
......
using System;
using System.Threading.Tasks;
using DotNetCore.CAP.Abstractions;
using DotNetCore.CAP.Internal;
using DotNetCore.CAP.Messages;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using Xunit;
namespace DotNetCore.CAP.Test
{
public class CallbackMessageSenderTest
{
private IServiceProvider _provider;
private Mock<ICallbackPublisher> _mockCallbackPublisher;
private Mock<IContentSerializer> _mockContentSerializer;
private Mock<IMessagePacker> _mockMessagePack;
public CallbackMessageSenderTest()
{
_mockCallbackPublisher = new Mock<ICallbackPublisher>();
_mockContentSerializer = new Mock<IContentSerializer>();
_mockMessagePack = new Mock<IMessagePacker>();
var services = new ServiceCollection();
services.AddTransient<CallbackMessageSender>();
services.AddLogging();
services.AddSingleton(_mockCallbackPublisher.Object);
services.AddSingleton(_mockContentSerializer.Object);
services.AddSingleton(_mockMessagePack.Object);
_provider = services.BuildServiceProvider();
}
[Fact]
public async void SendAsync_CanSend()
{
// Arrange
_mockCallbackPublisher
.Setup(x => x.PublishCallbackAsync(It.IsAny<CapPublishedMessage>()))
.Returns(Task.CompletedTask).Verifiable();
_mockContentSerializer
.Setup(x => x.Serialize(It.IsAny<object>()))
.Returns("").Verifiable();
_mockMessagePack
.Setup(x => x.Pack(It.IsAny<CapMessage>()))
.Returns("").Verifiable();
var fixture = Create();
// Act
await fixture.SendAsync(null, null, Mock.Of<object>());
// Assert
_mockCallbackPublisher.VerifyAll();
_mockContentSerializer.Verify();
_mockMessagePack.Verify();
}
private CallbackMessageSender Create()
=> _provider.GetService<CallbackMessageSender>();
}
}
namespace Samples
{
public interface IFoo
{
int Age { get; set; }
string Name { get; set; }
}
public class FooTest
{
[Fact]
public void CanSetProperty()
{
var mockFoo = new Mock<IFoo>();
mockFoo.Setup(x => x.Name).Returns("NameProerties");
Assert.Equal("NameProerties", mockFoo.Object.Name);
}
}
}
using System;
using System.Linq;
using System.Reflection;
using DotNetCore.CAP.Abstractions;
using DotNetCore.CAP.Internal;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using Xunit;
namespace DotNetCore.CAP.Test
{
public class ConsumerInvokerFactoryTest
{
private IServiceProvider _serviceProvider;
private Mock<IContentSerializer> _mockSerialiser;
private Mock<IMessagePacker> _mockMessagePacker;
private Mock<IModelBinderFactory> _mockModelBinderFactory;
public ConsumerInvokerFactoryTest()
{
_mockSerialiser = new Mock<IContentSerializer>();
_mockMessagePacker = new Mock<IMessagePacker>();
_mockModelBinderFactory = new Mock<IModelBinderFactory>();
var services = new ServiceCollection();
services.AddSingleton<ConsumerInvokerFactory>();
services.AddLogging();
services.AddSingleton(_mockSerialiser.Object);
services.AddSingleton(_mockMessagePacker.Object);
services.AddSingleton(_mockModelBinderFactory.Object);
_serviceProvider = services.BuildServiceProvider();
}
private ConsumerInvokerFactory Create() =>
_serviceProvider.GetService<ConsumerInvokerFactory>();
[Fact]
public void CreateInvokerTest()
{
// Arrange
var fixure = Create();
// Act
var invoker = fixure.CreateInvoker();
// Assert
Assert.NotNull(invoker);
}
[Theory]
[InlineData(nameof(Sample.ThrowException))]
[InlineData(nameof(Sample.AsyncMethod))]
public void InvokeMethodTest(string methodName)
{
// Arrange
var fixure = Create();
var methodInfo = typeof(Sample).GetRuntimeMethods()
.Single(x => x.Name == methodName);
var description = new ConsumerExecutorDescriptor
{
MethodInfo = methodInfo,
ImplTypeInfo = typeof(Sample).GetTypeInfo()
};
var messageContext = new MessageContext();
var context = new ConsumerContext(description, messageContext);
var invoker = fixure.CreateInvoker();
Assert.Throws<Exception>(() =>
{
invoker.InvokeAsync(context).GetAwaiter().GetResult();
});
}
}
}
\ No newline at end of file
using System;
using System.Reflection;
using System.Threading.Tasks;
using DotNetCore.CAP.Abstractions;
using DotNetCore.CAP.Infrastructure;
using DotNetCore.CAP.Messages;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using Xunit;
namespace DotNetCore.CAP.Test
{
public class ConsumerInvokerTest
{
private ILoggerFactory _loggerFactory;
private Mock<IMessagePacker> _mockMessagePacker;
private Mock<IModelBinderFactory> _mockModelBinderFactory;
private MessageContext _messageContext;
public ConsumerInvokerTest()
{
_loggerFactory = new NullLoggerFactory();
_mockMessagePacker = new Mock<IMessagePacker>();
_mockModelBinderFactory = new Mock<IModelBinderFactory>();
}
private Internal.DefaultConsumerInvoker InitDefaultConsumerInvoker(IServiceProvider provider)
{
var invoker = new Internal.DefaultConsumerInvoker(
_loggerFactory,
provider,
_mockMessagePacker.Object,
_mockModelBinderFactory.Object);
var message = new CapReceivedMessage
{
Id = SnowflakeId.Default().NextId(),
Name = "test",
Content = DateTime.Now.ToString(),
StatusName = StatusName.Scheduled,
Group = "Group.Test"
};
_mockMessagePacker
.Setup(x => x.UnPack(It.IsAny<string>()))
.Returns(new CapMessageDto(message.Content));
_messageContext = new MessageContext
{
Group = message.Group,
Name = message.Name,
Content = Helper.ToJson(message)
};
return invoker;
}
[Fact]
public async Task CanInvokeServiceTest()
{
var services = new ServiceCollection();
services.AddSingleton<ITestService, TestService2>();
services.AddSingleton<ITestService, TestService>();
var provider = services.BuildServiceProvider();
var invoker = InitDefaultConsumerInvoker(provider);
var descriptor = new ConsumerExecutorDescriptor
{
ServiceTypeInfo = typeof(ITestService).GetTypeInfo(),
ImplTypeInfo = typeof(TestService).GetTypeInfo(),
MethodInfo = typeof(TestService).GetMethod("Index")
};
descriptor.Attribute = descriptor.MethodInfo.GetCustomAttribute<TopicAttribute>(true);
var context = new Internal.ConsumerContext(descriptor, _messageContext);
var result = await invoker.InvokeAsync(context);
Assert.NotNull(result);
Assert.NotNull(result.Result);
Assert.Equal("test", result.Result.ToString());
}
[Fact]
public async Task CanInvokeControllerTest()
{
var services = new ServiceCollection();
var provider = services.BuildServiceProvider();
var invoker = InitDefaultConsumerInvoker(provider);
var descriptor = new ConsumerExecutorDescriptor
{
ServiceTypeInfo = typeof(HomeController).GetTypeInfo(),
ImplTypeInfo = typeof(HomeController).GetTypeInfo(),
MethodInfo = typeof(HomeController).GetMethod("Index")
};
descriptor.Attribute = descriptor.MethodInfo.GetCustomAttribute<TopicAttribute>(true);
var context = new Internal.ConsumerContext(descriptor, _messageContext);
var result = await invoker.InvokeAsync(context);
Assert.NotNull(result);
Assert.NotNull(result.Result);
Assert.Equal("test", result.Result.ToString());
}
}
public class HomeController
{
[CapSubscribe("test")]
public string Index()
{
return "test";
}
}
public interface ITestService { }
public class TestService : ITestService, ICapSubscribe
{
[CapSubscribe("test")]
public string Index()
{
return "test";
}
}
public class TestService2 : ITestService
{
[CapSubscribe("test")]
public string Index()
{
return "test2";
}
}
public class CapSubscribeAttribute : TopicAttribute
{
public CapSubscribeAttribute(string name) : base(name)
{
}
}
}
\ No newline at end of file
using System;
using System.Threading.Tasks;
using DotNetCore.CAP.Abstractions;
using DotNetCore.CAP.Internal;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
......
......@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using DotNetCore.CAP.Internal;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Xunit;
......
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using DotNetCore.CAP.Diagnostics;
using DotNetCore.CAP.Internal;
using Xunit;
namespace DotNetCore.CAP.Test
{
public class DiagnosticsTest
{
private static readonly DiagnosticListener s_diagnosticListener =
new DiagnosticListener(CapDiagnosticListenerExtensions.DiagnosticListenerName);
[Fact]
public void WritePublishBeforeTest()
{
Guid operationId = Guid.NewGuid();
DiagnosticsWapper(() =>
{
var eventData = new BrokerPublishEventData(operationId, "", "", "", "", DateTimeOffset.UtcNow);
s_diagnosticListener.WritePublishBefore(eventData);
}, kvp =>
{
if (kvp.Key.Equals(CapDiagnosticListenerExtensions.CapBeforePublish))
{
Assert.NotNull(kvp.Value);
Assert.IsType<BrokerPublishEventData>(kvp.Value);
Assert.Equal(operationId, ((BrokerPublishEventData)kvp.Value).OperationId);
}
});
}
[Fact]
public void WritePublishAfterTest()
{
Guid operationId = Guid.NewGuid();
DiagnosticsWapper(() =>
{
var eventData = new BrokerPublishEndEventData(operationId, "", "", "", "", DateTimeOffset.UtcNow, TimeSpan.FromMinutes(1));
s_diagnosticListener.WritePublishAfter(eventData);
}, kvp =>
{
if (kvp.Key.Equals(CapDiagnosticListenerExtensions.CapAfterPublish))
{
Assert.NotNull(kvp.Value);
Assert.IsType<BrokerPublishEndEventData>(kvp.Value);
Assert.Equal(operationId, ((BrokerPublishEndEventData)kvp.Value).OperationId);
Assert.Equal(TimeSpan.FromMinutes(1), ((BrokerPublishEndEventData)kvp.Value).Duration);
}
});
}
[Fact]
public void WritePublishErrorTest()
{
Guid operationId = Guid.NewGuid();
var ex = new Exception("WritePublishErrorTest");
DiagnosticsWapper(() =>
{
var eventData = new BrokerPublishErrorEventData(operationId, "", "", "", "", ex, DateTimeOffset.UtcNow, default(TimeSpan));
s_diagnosticListener.WritePublishError(eventData);
}, kvp =>
{
if (kvp.Key.Equals(CapDiagnosticListenerExtensions.CapErrorPublish))
{
Assert.NotNull(kvp.Value);
Assert.IsType<BrokerPublishErrorEventData>(kvp.Value);
Assert.Equal(operationId, ((BrokerPublishErrorEventData)kvp.Value).OperationId);
Assert.Equal(ex, ((BrokerPublishErrorEventData)kvp.Value).Exception);
}
});
}
[Fact]
public void WriteConsumeBeforeTest()
{
Guid operationId = Guid.NewGuid();
DiagnosticsWapper(() =>
{
var eventData = new BrokerConsumeEventData(operationId, "", "", "", "", DateTimeOffset.UtcNow);
s_diagnosticListener.WriteConsumeBefore(eventData);
}, kvp =>
{
if (kvp.Key.Equals(CapDiagnosticListenerExtensions.CapBeforeConsume))
{
Assert.NotNull(kvp.Value);
Assert.IsType<BrokerConsumeEventData>(kvp.Value);
Assert.Equal(operationId, ((BrokerConsumeEventData)kvp.Value).OperationId);
}
});
}
[Fact]
public void WriteConsumeAfterTest()
{
Guid operationId = Guid.NewGuid();
DiagnosticsWapper(() =>
{
var eventData = new BrokerConsumeEndEventData(operationId, "", "", "", "", DateTimeOffset.UtcNow, TimeSpan.FromMinutes(1));
s_diagnosticListener.WriteConsumeAfter(eventData);
}, kvp =>
{
if (kvp.Key.Equals(CapDiagnosticListenerExtensions.CapAfterConsume))
{
Assert.NotNull(kvp.Value);
Assert.IsType<BrokerConsumeEndEventData>(kvp.Value);
Assert.Equal(operationId, ((BrokerConsumeEndEventData)kvp.Value).OperationId);
Assert.Equal(TimeSpan.FromMinutes(1), ((BrokerConsumeEndEventData)kvp.Value).Duration);
}
});
}
[Fact]
public void WriteConsumeErrorTest()
{
Guid operationId = Guid.NewGuid();
var ex = new Exception("WriteConsumeErrorTest");
DiagnosticsWapper(() =>
{
var eventData = new BrokerConsumeErrorEventData(operationId, "", "", "", "", ex, DateTimeOffset.UtcNow, default(TimeSpan));
s_diagnosticListener.WriteConsumeError(eventData);
}, kvp =>
{
if (kvp.Key.Equals(CapDiagnosticListenerExtensions.CapErrorPublish))
{
Assert.NotNull(kvp.Value);
Assert.IsType<BrokerConsumeErrorEventData>(kvp.Value);
Assert.Equal(operationId, ((BrokerConsumeErrorEventData)kvp.Value).OperationId);
Assert.Equal(ex, ((BrokerConsumeErrorEventData)kvp.Value).Exception);
}
});
}
[Fact]
public void WriteSubscriberInvokeBeforeTest()
{
DiagnosticsWapper(() =>
{
s_diagnosticListener.WriteSubscriberInvokeBefore(FackConsumerContext());
}, kvp =>
{
if (kvp.Key.Equals(CapDiagnosticListenerExtensions.CapBeforeSubscriberInvoke))
{
Assert.NotNull(kvp.Value);
Assert.IsType<SubscriberInvokeEventData>(kvp.Value);
}
});
}
[Fact]
public void WriteSubscriberInvokeAfterTest()
{
Guid operationId = Guid.NewGuid();
DiagnosticsWapper(() =>
{
s_diagnosticListener.WriteSubscriberInvokeAfter(operationId, FackConsumerContext(), DateTimeOffset.Now, TimeSpan.FromMinutes(1));
}, kvp =>
{
if (kvp.Key.Equals(CapDiagnosticListenerExtensions.CapAfterSubscriberInvoke))
{
Assert.NotNull(kvp.Value);
Assert.IsType<SubscriberInvokeEndEventData>(kvp.Value);
Assert.Equal(operationId, ((SubscriberInvokeEndEventData)kvp.Value).OperationId);
}
});
}
[Fact]
public void WriteSubscriberInvokeErrorTest()
{
Guid operationId = Guid.NewGuid();
var ex = new Exception("WriteConsumeErrorTest");
DiagnosticsWapper(() =>
{
s_diagnosticListener.WriteSubscriberInvokeError(operationId, FackConsumerContext(), ex,
DateTimeOffset.Now, TimeSpan.MaxValue);
}, kvp =>
{
if (kvp.Key.Equals(CapDiagnosticListenerExtensions.CapErrorSubscriberInvoke))
{
Assert.NotNull(kvp.Value);
Assert.IsType<SubscriberInvokeErrorEventData>(kvp.Value);
Assert.Equal(operationId, ((SubscriberInvokeErrorEventData)kvp.Value).OperationId);
Assert.Equal(ex, ((SubscriberInvokeErrorEventData)kvp.Value).Exception);
}
});
}
private ConsumerContext FackConsumerContext()
{
//Mock description
var description = new ConsumerExecutorDescriptor
{
MethodInfo = GetType().GetMethod("WriteSubscriberInvokeAfterTest"),
Attribute = new CapSubscribeAttribute("xxx"),
ImplTypeInfo = GetType().GetTypeInfo()
};
//Mock messageContext
var messageContext = new MessageContext
{
Name= "Name",
Group= "Group",
Content = "Content"
};
return new ConsumerContext(description, messageContext);
}
private void DiagnosticsWapper(Action operation, Action<KeyValuePair<string, object>> assert, [CallerMemberName]string methodName = "")
{
FakeDiagnosticListenerObserver diagnosticListenerObserver = new FakeDiagnosticListenerObserver(assert);
diagnosticListenerObserver.Enable();
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
Console.WriteLine(string.Format("Test: {0} Enabled Listeners", methodName));
operation();
}
}
}
}
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using DotNetCore.CAP.Diagnostics;
namespace DotNetCore.CAP.Test
{
public sealed class FakeDiagnosticListenerObserver : IObserver<DiagnosticListener>
{
private class FakeDiagnosticSourceWriteObserver : IObserver<KeyValuePair<string, object>>
{
private readonly Action<KeyValuePair<string, object>> _writeCallback;
public FakeDiagnosticSourceWriteObserver(Action<KeyValuePair<string, object>> writeCallback)
{
_writeCallback = writeCallback;
}
public void OnCompleted()
{
}
public void OnError(Exception error)
{
}
public void OnNext(KeyValuePair<string, object> value)
{
_writeCallback(value);
}
}
private readonly Action<KeyValuePair<string, object>> _writeCallback;
private bool _writeObserverEnabled;
public FakeDiagnosticListenerObserver(Action<KeyValuePair<string, object>> writeCallback)
{
_writeCallback = writeCallback;
}
public void OnCompleted()
{
}
public void OnError(Exception error)
{
}
public void OnNext(DiagnosticListener value)
{
if (value.Name.Equals(CapDiagnosticListenerExtensions.DiagnosticListenerName))
{
value.Subscribe(new FakeDiagnosticSourceWriteObserver(_writeCallback), IsEnabled);
}
}
public void Enable()
{
_writeObserverEnabled = true;
}
public void Disable()
{
_writeObserverEnabled = false;
}
private bool IsEnabled(string s)
{
return _writeObserverEnabled;
}
}
}
using System;
using System.Reflection;
using DotNetCore.CAP.Diagnostics;
using DotNetCore.CAP.Infrastructure;
using Newtonsoft.Json.Linq;
using DotNetCore.CAP.Internal;
using Xunit;
namespace DotNetCore.CAP.Test
{
public class HelperTest
{
[Fact]
public void ToTimestampTest()
{
......@@ -23,19 +20,6 @@ namespace DotNetCore.CAP.Test
Assert.Equal(1514764800, result);
}
[Fact]
public void FromTimestampTest()
{
//Arrange
var time = DateTime.Parse("2018-01-01 00:00:00");
//Act
var result = Helper.FromTimestamp(1514764800);
//Assert
Assert.Equal(time, result);
}
[Fact]
public void IsControllerTest()
{
......@@ -69,7 +53,6 @@ namespace DotNetCore.CAP.Test
[Theory]
[InlineData(typeof(HomeController))]
[InlineData(typeof(Exception))]
[InlineData(typeof(Person))]
public void IsComplexTypeTest(Type type)
{
//Act
......@@ -79,36 +62,6 @@ namespace DotNetCore.CAP.Test
Assert.True(result);
}
[Fact]
public void AddExceptionPropertyTest()
{
//Arrange
var json = "{}";
var exception = new Exception("Test Exception Message")
{
Source = "Test Source",
InnerException = { }
};
var expected = new
{
ExceptionMessage = new
{
Source = "Test Source",
Message = "Test Exception Message",
InnerMessage = new { }
}
};
//Act
var result = Helper.AddExceptionProperty(json, exception);
//Assert
var jObj = JObject.Parse(result);
Assert.Equal(jObj["ExceptionMessage"]["Source"].Value<string>(), expected.ExceptionMessage.Source);
Assert.Equal(jObj["ExceptionMessage"]["Message"].Value<string>(), expected.ExceptionMessage.Message);
}
[Theory]
[InlineData("10.0.0.1")]
[InlineData("172.16.0.1")]
......@@ -117,38 +70,10 @@ namespace DotNetCore.CAP.Test
{
Assert.True(Helper.IsInnerIP(ipAddress));
}
[Fact]
public void AddTracingHeaderPropertyTest()
{
//Arrange
var json = "{}";
var header = new TracingHeaders { { "key", "value" } };
//Act
var result = Helper.AddTracingHeaderProperty(json, header);
//Assert
var expected = "{\"TracingHeaders\":{\"key\":\"value\"}}";
Assert.Equal(expected, result);
}
[Fact]
public void TryExtractTracingHeadersTest()
class HomeController
{
//Arrange
var json = "{\"TracingHeaders\":{\"key\":\"value\"}}";
TracingHeaders header = null;
string removedHeadersJson = "";
//Act
var result = Helper.TryExtractTracingHeaders(json, out header, out removedHeadersJson);
//Assert
Assert.True(result);
Assert.NotNull(header);
Assert.Single(header);
Assert.Equal("{}", removedHeadersJson);
}
}
}
using System;
using DotNetCore.CAP.Internal;
using DotNetCore.CAP.Messages;
using Newtonsoft.Json;
using Xunit;
namespace DotNetCore.CAP.Test
{
public class JsonContentSerializerTest
{
[Fact]
public void CanSerialize()
{
//Arrange
var fixtrue = Create();
var message = new CapMessageDto
{
Id = "1",
Content = "Content",
CallbackName = "Callback",
Timestamp = DateTime.Now
};
//Act
var ret = fixtrue.Serialize(message);
//Assert
var expected = JsonConvert.SerializeObject(message);
Assert.NotNull(ret);
Assert.Equal(expected, ret);
}
[Fact]
public void CanDeSerialize()
{
//Arrange
var fixtrue = Create();
var message = new CapMessageDto
{
Id = "1",
Content = "Content",
CallbackName = "Callback",
Timestamp = DateTime.Now
};
var messageJson = JsonConvert.SerializeObject(message);
//Act
var ret = fixtrue.DeSerialize<CapMessageDto>(messageJson);
//Assert
Assert.NotNull(ret);
Assert.Equal(message.Id, ret.Id);
Assert.Equal(message.Content, ret.Content);
Assert.Equal(message.CallbackName, ret.CallbackName);
Assert.Equal(message.Timestamp, ret.Timestamp);
}
private JsonContentSerializer Create() => new JsonContentSerializer();
}
}
using System;
using DotNetCore.CAP.Infrastructure;
using DotNetCore.CAP.Messages;
using DotNetCore.CAP.Processor.States;
using Moq;
using Xunit;
namespace DotNetCore.CAP.Test
{
public class StateChangerTest
{
[Fact]
public void ChangeState()
{
// Arrange
var fixture = Create();
var message = new CapPublishedMessage
{
Id = SnowflakeId.Default().NextId(),
StatusName = StatusName.Scheduled
};
var state = Mock.Of<IState>(s => s.Name == "s" && s.ExpiresAfter == null);
var mockTransaction = new Mock<IStorageTransaction>();
// Act
fixture.ChangeState(message, state, mockTransaction.Object);
// Assert
Assert.Equal("s", message.StatusName);
Assert.Null(message.ExpiresAt);
Mock.Get(state).Verify(s => s.Apply(message, mockTransaction.Object), Times.Once);
mockTransaction.Verify(t => t.UpdateMessage(message), Times.Once);
mockTransaction.Verify(t => t.CommitAsync(), Times.Never);
}
[Fact]
public void ChangeState_ExpiresAfter()
{
// Arrange
var fixture = Create();
var message = new CapPublishedMessage
{
Id = SnowflakeId.Default().NextId(),
StatusName = StatusName.Scheduled
};
var state = Mock.Of<IState>(s => s.Name == "s" && s.ExpiresAfter == TimeSpan.FromHours(1));
var mockTransaction = new Mock<IStorageTransaction>();
// Act
fixture.ChangeState(message, state, mockTransaction.Object);
// Assert
Assert.Equal("s", message.StatusName);
Assert.NotNull(message.ExpiresAt);
mockTransaction.Verify(t => t.UpdateMessage(message), Times.Once);
mockTransaction.Verify(t => t.CommitAsync(), Times.Never);
}
private StateChanger Create() => new StateChanger();
}
}
\ No newline at end of file
//using System;
//using DotNetCore.CAP.Internal;
//using Microsoft.Extensions.DependencyInjection;
//using Xunit;
//using Moq;
//namespace DotNetCore.CAP.Test
//{
// public class QueueExecutorFactoryTest
// {
// private IServiceProvider _provider;
// public QueueExecutorFactoryTest()
// {
// var services = new ServiceCollection();
// services.AddLogging();
// services.AddOptions();
// services.AddCap(x => { });
// _provider = services.BuildServiceProvider();
// }
// [Fact]
// public void CanCreateInstance()
// {
// var queueExecutorFactory = _provider.GetService<IQueueExecutorFactory>();
// Assert.NotNull(queueExecutorFactory);
// var publishExecutor = queueExecutorFactory.GetInstance(Models.MessageType.Publish);
// Assert.Null(publishExecutor);
// var disPatchExector = queueExecutorFactory.GetInstance(Models.MessageType.Subscribe);
// Assert.NotNull(disPatchExector);
// }
// [Fact]
// public void CanGetSubscribeExector()
// {
// var queueExecutorFactory = _provider.GetService<IQueueExecutorFactory>();
// Assert.NotNull(queueExecutorFactory);
// var publishExecutor = queueExecutorFactory.GetInstance(Models.MessageType.Publish);
// Assert.Null(publishExecutor);
// }
// }
//}
\ No newline at end of file
using System;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Xunit;
namespace DotNetCore.CAP.Test
{
public class Sample
{
public void DateTimeParam(DateTime dateTime)
{
}
public void StringParam(string @string)
{
}
public void GuidParam(Guid guid)
{
}
public void UriParam(Uri uri)
{
}
public void IntegerParam(int @int)
{
}
public void ComplexTypeParam(ComplexType complexType)
{
}
public void ThrowException()
{
throw new Exception();
}
public async Task<int> AsyncMethod()
{
await Task.FromResult(3);
throw new Exception();
}
}
public class ComplexType
{
public DateTime Time { get; set; }
public string String { get; set; }
public Guid Guid { get; set; }
public Person Person { get; set; }
}
public class Person
{
public int Age { get; set; }
public string Name { get; set; }
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment