diff --git a/src/NSubstitute/Compatibility/DiagnosticsNullabilityAttributes.cs b/src/NSubstitute/Compatibility/DiagnosticsNullabilityAttributes.cs index e3cdd540..f717db57 100644 --- a/src/NSubstitute/Compatibility/DiagnosticsNullabilityAttributes.cs +++ b/src/NSubstitute/Compatibility/DiagnosticsNullabilityAttributes.cs @@ -22,45 +22,39 @@ internal sealed class MaybeNullAttribute : Attribute { } internal sealed class NotNullAttribute : Attribute { } /// Specifies that when a method returns , the parameter may be null even if the corresponding type disallows it. +/// Initializes the attribute with the specified return value condition. +/// +/// The return value condition. If the method returns this value, the associated parameter may be null. +/// [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] -internal sealed class MaybeNullWhenAttribute : Attribute +internal sealed class MaybeNullWhenAttribute(bool returnValue) : Attribute { - /// Initializes the attribute with the specified return value condition. - /// - /// The return value condition. If the method returns this value, the associated parameter may be null. - /// - public MaybeNullWhenAttribute(bool returnValue) => ReturnValue = returnValue; - /// Gets the return value condition. - public bool ReturnValue { get; } + public bool ReturnValue { get; } = returnValue; } /// Specifies that when a method returns , the parameter will not be null even if the corresponding type allows it. +/// Initializes the attribute with the specified return value condition. +/// +/// The return value condition. If the method returns this value, the associated parameter will not be null. +/// [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] -internal sealed class NotNullWhenAttribute : Attribute +internal sealed class NotNullWhenAttribute(bool returnValue) : Attribute { - /// Initializes the attribute with the specified return value condition. - /// - /// The return value condition. If the method returns this value, the associated parameter will not be null. - /// - public NotNullWhenAttribute(bool returnValue) => ReturnValue = returnValue; - /// Gets the return value condition. - public bool ReturnValue { get; } + public bool ReturnValue { get; } = returnValue; } /// Specifies that the output will be non-null if the named parameter is non-null. +/// Initializes the attribute with the associated parameter name. +/// +/// The associated parameter name. The output will be non-null if the argument to the parameter specified is non-null. +/// [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] -internal sealed class NotNullIfNotNullAttribute : Attribute +internal sealed class NotNullIfNotNullAttribute(string parameterName) : Attribute { - /// Initializes the attribute with the associated parameter name. - /// - /// The associated parameter name. The output will be non-null if the argument to the parameter specified is non-null. - /// - public NotNullIfNotNullAttribute(string parameterName) => ParameterName = parameterName; - /// Gets the associated parameter name. - public string ParameterName { get; } + public string ParameterName { get; } = parameterName; } /// Applied to a method that will never return under any circumstance. @@ -68,18 +62,16 @@ internal sealed class NotNullIfNotNullAttribute : Attribute internal sealed class DoesNotReturnAttribute : Attribute { } /// Specifies that the method will not return if the associated Boolean parameter is passed the specified value. +/// Initializes the attribute with the specified parameter value. +/// +/// The condition parameter value. Code after the method will be considered unreachable by diagnostics if the argument to +/// the associated parameter matches this value. +/// [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] -internal sealed class DoesNotReturnIfAttribute : Attribute +internal sealed class DoesNotReturnIfAttribute(bool parameterValue) : Attribute { - /// Initializes the attribute with the specified parameter value. - /// - /// The condition parameter value. Code after the method will be considered unreachable by diagnostics if the argument to - /// the associated parameter matches this value. - /// - public DoesNotReturnIfAttribute(bool parameterValue) => ParameterValue = parameterValue; - /// Gets the condition parameter value. - public bool ParameterValue { get; } + public bool ParameterValue { get; } = parameterValue; } /// Specifies that the method or property will ensure that the listed field and property members have not-null values. diff --git a/src/NSubstitute/Core/ArgumentSpecificationDequeue.cs b/src/NSubstitute/Core/ArgumentSpecificationDequeue.cs index 7dfd76d8..81e6d481 100644 --- a/src/NSubstitute/Core/ArgumentSpecificationDequeue.cs +++ b/src/NSubstitute/Core/ArgumentSpecificationDequeue.cs @@ -3,17 +3,10 @@ namespace NSubstitute.Core; -public class ArgumentSpecificationDequeue : IArgumentSpecificationDequeue +public class ArgumentSpecificationDequeue(Func> dequeueAllQueuedArgSpecs) : IArgumentSpecificationDequeue { private static readonly IArgumentSpecification[] EmptySpecifications = []; - private readonly Func> _dequeueAllQueuedArgSpecs; - - public ArgumentSpecificationDequeue(Func> dequeueAllQueuedArgSpecs) - { - _dequeueAllQueuedArgSpecs = dequeueAllQueuedArgSpecs; - } - public IList DequeueAllArgumentSpecificationsForMethod(int parametersCount) { if (parametersCount == 0) @@ -24,7 +17,7 @@ public IList DequeueAllArgumentSpecificationsForMethod(i return EmptySpecifications; } - var queuedArgSpecifications = _dequeueAllQueuedArgSpecs.Invoke(); + var queuedArgSpecifications = dequeueAllQueuedArgSpecs.Invoke(); return queuedArgSpecifications; } diff --git a/src/NSubstitute/Core/Arguments/AnyArgumentMatcher.cs b/src/NSubstitute/Core/Arguments/AnyArgumentMatcher.cs index 2f46784c..82b083d0 100644 --- a/src/NSubstitute/Core/Arguments/AnyArgumentMatcher.cs +++ b/src/NSubstitute/Core/Arguments/AnyArgumentMatcher.cs @@ -1,15 +1,8 @@ namespace NSubstitute.Core.Arguments; -public class AnyArgumentMatcher : IArgumentMatcher +public class AnyArgumentMatcher(Type typeArgMustBeCompatibleWith) : IArgumentMatcher { - private readonly Type _typeArgMustBeCompatibleWith; + public override string ToString() => "any " + typeArgMustBeCompatibleWith.GetNonMangledTypeName(); - public AnyArgumentMatcher(Type typeArgMustBeCompatibleWith) - { - _typeArgMustBeCompatibleWith = typeArgMustBeCompatibleWith; - } - - public override string ToString() => "any " + _typeArgMustBeCompatibleWith.GetNonMangledTypeName(); - - public bool IsSatisfiedBy(object? argument) => argument.IsCompatibleWith(_typeArgMustBeCompatibleWith); + public bool IsSatisfiedBy(object? argument) => argument.IsCompatibleWith(typeArgMustBeCompatibleWith); } \ No newline at end of file diff --git a/src/NSubstitute/Core/Arguments/ArgumentMatchInfo.cs b/src/NSubstitute/Core/Arguments/ArgumentMatchInfo.cs index fc2d2303..508e10d6 100644 --- a/src/NSubstitute/Core/Arguments/ArgumentMatchInfo.cs +++ b/src/NSubstitute/Core/Arguments/ArgumentMatchInfo.cs @@ -1,17 +1,10 @@ namespace NSubstitute.Core.Arguments; -public class ArgumentMatchInfo +public class ArgumentMatchInfo(int index, object? argument, IArgumentSpecification specification) { - public ArgumentMatchInfo(int index, object? argument, IArgumentSpecification specification) - { - Index = index; - _argument = argument; - _specification = specification; - } - - private readonly object? _argument; - private readonly IArgumentSpecification _specification; - public int Index { get; } + private readonly object? _argument = argument; + private readonly IArgumentSpecification _specification = specification; + public int Index { get; } = index; public bool IsMatch => _specification.IsSatisfiedBy(_argument); diff --git a/src/NSubstitute/Core/Arguments/ArgumentMatcher.cs b/src/NSubstitute/Core/Arguments/ArgumentMatcher.cs index f4d4bbee..2695a2cf 100644 --- a/src/NSubstitute/Core/Arguments/ArgumentMatcher.cs +++ b/src/NSubstitute/Core/Arguments/ArgumentMatcher.cs @@ -33,14 +33,9 @@ public static class ArgumentMatcher return ref new DefaultValueContainer().Value; } - private class GenericToNonGenericMatcherProxy : IArgumentMatcher + private class GenericToNonGenericMatcherProxy(IArgumentMatcher matcher) : IArgumentMatcher { - protected readonly IArgumentMatcher _matcher; - - public GenericToNonGenericMatcherProxy(IArgumentMatcher matcher) - { - _matcher = matcher; - } + protected readonly IArgumentMatcher _matcher = matcher; public bool IsSatisfiedBy(object? argument) => _matcher.IsSatisfiedBy((T?)argument!); } diff --git a/src/NSubstitute/Core/Arguments/ArgumentSpecification.cs b/src/NSubstitute/Core/Arguments/ArgumentSpecification.cs index 67147f0b..5dca300d 100644 --- a/src/NSubstitute/Core/Arguments/ArgumentSpecification.cs +++ b/src/NSubstitute/Core/Arguments/ArgumentSpecification.cs @@ -1,23 +1,13 @@ namespace NSubstitute.Core.Arguments; -public class ArgumentSpecification : IArgumentSpecification +public class ArgumentSpecification(Type forType, IArgumentMatcher matcher, Action action) : IArgumentSpecification { private static readonly Action NoOpAction = _ => { }; - - private readonly IArgumentMatcher _matcher; - private readonly Action _action; - public Type ForType { get; } - public bool HasAction => _action != NoOpAction; + public Type ForType { get; } = forType; + public bool HasAction => action != NoOpAction; public ArgumentSpecification(Type forType, IArgumentMatcher matcher) : this(forType, matcher, NoOpAction) { } - public ArgumentSpecification(Type forType, IArgumentMatcher matcher, Action action) - { - ForType = forType; - _matcher = matcher; - _action = action; - } - public bool IsSatisfiedBy(object? argument) { if (!IsCompatibleWith(argument)) @@ -27,7 +17,7 @@ public bool IsSatisfiedBy(object? argument) try { - return _matcher.IsSatisfiedBy(argument); + return matcher.IsSatisfiedBy(argument); } catch { @@ -42,7 +32,7 @@ public string DescribeNonMatch(object? argument) return GetIncompatibleTypeMessage(argument); } - return _matcher is IDescribeNonMatches describe + return matcher is IDescribeNonMatches describe ? describe.DescribeFor(argument) : string.Empty; } @@ -51,12 +41,12 @@ public string FormatArgument(object? argument) { var isSatisfiedByArg = IsSatisfiedBy(argument); - return _matcher is IArgumentFormatter matcherFormatter + return matcher is IArgumentFormatter matcherFormatter ? matcherFormatter.Format(argument, highlight: !isSatisfiedByArg) : ArgumentFormatter.Default.Format(argument, highlight: !isSatisfiedByArg); } - public override string ToString() => _matcher.ToString() ?? string.Empty; + public override string ToString() => matcher.ToString() ?? string.Empty; public IArgumentSpecification CreateCopyMatchingAnyArgOfType(Type requiredType) { @@ -65,19 +55,19 @@ public IArgumentSpecification CreateCopyMatchingAnyArgOfType(Type requiredType) return new ArgumentSpecification( requiredType, new AnyArgumentMatcher(requiredType), - _action == NoOpAction ? NoOpAction : RunActionIfTypeIsCompatible); + action == NoOpAction ? NoOpAction : RunActionIfTypeIsCompatible); } public void RunAction(object? argument) { - _action(argument); + action(argument); } private void RunActionIfTypeIsCompatible(object? argument) { if (argument.IsCompatibleWith(ForType)) { - _action(argument); + action(argument); } } diff --git a/src/NSubstitute/Core/Arguments/ArgumentSpecificationCompatibilityTester.cs b/src/NSubstitute/Core/Arguments/ArgumentSpecificationCompatibilityTester.cs index 05dbe80e..866b09c7 100644 --- a/src/NSubstitute/Core/Arguments/ArgumentSpecificationCompatibilityTester.cs +++ b/src/NSubstitute/Core/Arguments/ArgumentSpecificationCompatibilityTester.cs @@ -1,14 +1,7 @@ namespace NSubstitute.Core.Arguments; -public class ArgumentSpecificationCompatibilityTester : IArgumentSpecificationCompatibilityTester +public class ArgumentSpecificationCompatibilityTester(IDefaultChecker defaultChecker) : IArgumentSpecificationCompatibilityTester { - private readonly IDefaultChecker _defaultChecker; - - public ArgumentSpecificationCompatibilityTester(IDefaultChecker defaultChecker) - { - _defaultChecker = defaultChecker; - } - public bool IsSpecificationCompatible(IArgumentSpecification specification, object? argumentValue, Type argumentType) { var typeArgSpecIsFor = specification.ForType; @@ -18,7 +11,7 @@ public bool IsSpecificationCompatible(IArgumentSpecification specification, obje private bool IsProvidedArgumentTheOneWeWouldGetUsingAnArgSpecForThisType(object? argument, Type typeArgSpecIsFor) { - return _defaultChecker.IsDefault(argument, typeArgSpecIsFor); + return defaultChecker.IsDefault(argument, typeArgSpecIsFor); } private bool AreTypesCompatible(Type argumentType, Type typeArgSpecIsFor) diff --git a/src/NSubstitute/Core/Arguments/ArgumentSpecificationFactory.cs b/src/NSubstitute/Core/Arguments/ArgumentSpecificationFactory.cs index ed0945bc..a415f906 100644 --- a/src/NSubstitute/Core/Arguments/ArgumentSpecificationFactory.cs +++ b/src/NSubstitute/Core/Arguments/ArgumentSpecificationFactory.cs @@ -80,14 +80,9 @@ private IEnumerable UnwrapParamsArguments(IEnumerable false; diff --git a/src/NSubstitute/Core/Arguments/ArgumentSpecificationsFactory.cs b/src/NSubstitute/Core/Arguments/ArgumentSpecificationsFactory.cs index 109af96a..98c2a630 100644 --- a/src/NSubstitute/Core/Arguments/ArgumentSpecificationsFactory.cs +++ b/src/NSubstitute/Core/Arguments/ArgumentSpecificationsFactory.cs @@ -1,22 +1,15 @@ -using System.Reflection; -using NSubstitute.Exceptions; +using NSubstitute.Exceptions; +using System.Reflection; namespace NSubstitute.Core.Arguments; -public class ArgumentSpecificationsFactory : IArgumentSpecificationsFactory +public class ArgumentSpecificationsFactory( + IArgumentSpecificationFactory argumentSpecificationFactory, + ISuppliedArgumentSpecificationsFactory suppliedArgumentSpecificationsFactory) : IArgumentSpecificationsFactory { - private readonly IArgumentSpecificationFactory _argumentSpecificationFactory; - private readonly ISuppliedArgumentSpecificationsFactory _suppliedArgumentSpecificationsFactory; - - public ArgumentSpecificationsFactory(IArgumentSpecificationFactory argumentSpecificationFactory, ISuppliedArgumentSpecificationsFactory suppliedArgumentSpecificationsFactory) - { - _argumentSpecificationFactory = argumentSpecificationFactory; - _suppliedArgumentSpecificationsFactory = suppliedArgumentSpecificationsFactory; - } - public IEnumerable Create(IList argumentSpecs, object?[] arguments, IParameterInfo[] parameterInfos, MethodInfo methodInfo, MatchArgs matchArgs) { - var suppliedArgumentSpecifications = _suppliedArgumentSpecificationsFactory.Create(argumentSpecs); + var suppliedArgumentSpecifications = suppliedArgumentSpecificationsFactory.Create(argumentSpecs); var result = new List(); for (var i = 0; i < arguments.Length; i++) @@ -26,7 +19,7 @@ public IEnumerable Create(IList try { - result.Add(_argumentSpecificationFactory.Create(arg, paramInfo, suppliedArgumentSpecifications)); + result.Add(argumentSpecificationFactory.Create(arg, paramInfo, suppliedArgumentSpecifications)); } catch (AmbiguousArgumentsException ex) when (ex.ContainsDefaultMessage) { diff --git a/src/NSubstitute/Core/Arguments/ArrayContentsArgumentMatcher.cs b/src/NSubstitute/Core/Arguments/ArrayContentsArgumentMatcher.cs index ca7c66ac..623351fc 100644 --- a/src/NSubstitute/Core/Arguments/ArrayContentsArgumentMatcher.cs +++ b/src/NSubstitute/Core/Arguments/ArrayContentsArgumentMatcher.cs @@ -2,14 +2,9 @@ namespace NSubstitute.Core.Arguments; -public class ArrayContentsArgumentMatcher : IArgumentMatcher, IArgumentFormatter +public class ArrayContentsArgumentMatcher(IEnumerable argumentSpecifications) : IArgumentMatcher, IArgumentFormatter { - private readonly IArgumentSpecification[] _argumentSpecifications; - - public ArrayContentsArgumentMatcher(IEnumerable argumentSpecifications) - { - _argumentSpecifications = argumentSpecifications.ToArray(); - } + private readonly IArgumentSpecification[] _argumentSpecifications = argumentSpecifications.ToArray(); public bool IsSatisfiedBy(object? argument) { diff --git a/src/NSubstitute/Core/Arguments/DefaultChecker.cs b/src/NSubstitute/Core/Arguments/DefaultChecker.cs index f31f6249..30fd3b92 100644 --- a/src/NSubstitute/Core/Arguments/DefaultChecker.cs +++ b/src/NSubstitute/Core/Arguments/DefaultChecker.cs @@ -1,16 +1,9 @@ namespace NSubstitute.Core.Arguments; -public class DefaultChecker : IDefaultChecker +public class DefaultChecker(IDefaultForType defaultForType) : IDefaultChecker { - private readonly IDefaultForType _defaultForType; - - public DefaultChecker(IDefaultForType defaultForType) - { - _defaultForType = defaultForType; - } - public bool IsDefault(object? value, Type forType) { - return EqualityComparer.Default.Equals(value, _defaultForType.GetDefaultFor(forType)); + return EqualityComparer.Default.Equals(value, defaultForType.GetDefaultFor(forType)); } } \ No newline at end of file diff --git a/src/NSubstitute/Core/Arguments/EqualsArgumentMatcher.cs b/src/NSubstitute/Core/Arguments/EqualsArgumentMatcher.cs index 1494c605..ef6ed4a5 100644 --- a/src/NSubstitute/Core/Arguments/EqualsArgumentMatcher.cs +++ b/src/NSubstitute/Core/Arguments/EqualsArgumentMatcher.cs @@ -1,15 +1,8 @@ namespace NSubstitute.Core.Arguments; -public class EqualsArgumentMatcher : IArgumentMatcher +public class EqualsArgumentMatcher(object? value) : IArgumentMatcher { - private readonly object? _value; + public override string ToString() => ArgumentFormatter.Default.Format(value, false); - public EqualsArgumentMatcher(object? value) - { - _value = value; - } - - public override string ToString() => ArgumentFormatter.Default.Format(_value, false); - - public bool IsSatisfiedBy(object? argument) => EqualityComparer.Default.Equals(_value, argument); + public bool IsSatisfiedBy(object? argument) => EqualityComparer.Default.Equals(value, argument); } \ No newline at end of file diff --git a/src/NSubstitute/Core/Arguments/ExpressionArgumentMatcher.cs b/src/NSubstitute/Core/Arguments/ExpressionArgumentMatcher.cs index 860738a1..f7b7ab8e 100644 --- a/src/NSubstitute/Core/Arguments/ExpressionArgumentMatcher.cs +++ b/src/NSubstitute/Core/Arguments/ExpressionArgumentMatcher.cs @@ -2,16 +2,10 @@ namespace NSubstitute.Core.Arguments; -public class ExpressionArgumentMatcher : IArgumentMatcher +public class ExpressionArgumentMatcher(Expression> predicate) : IArgumentMatcher { - private readonly string _predicateDescription; - private readonly Predicate _predicate; - - public ExpressionArgumentMatcher(Expression> predicate) - { - _predicate = predicate.Compile(); - _predicateDescription = predicate.ToString(); - } + private readonly string _predicateDescription = predicate.ToString(); + private readonly Predicate _predicate = predicate.Compile(); public bool IsSatisfiedBy(object? argument) => _predicate((T?)argument!); diff --git a/src/NSubstitute/Core/Arguments/SuppliedArgumentSpecificationsFactory.cs b/src/NSubstitute/Core/Arguments/SuppliedArgumentSpecificationsFactory.cs index ec5904ae..c4b0145b 100644 --- a/src/NSubstitute/Core/Arguments/SuppliedArgumentSpecificationsFactory.cs +++ b/src/NSubstitute/Core/Arguments/SuppliedArgumentSpecificationsFactory.cs @@ -1,16 +1,9 @@ namespace NSubstitute.Core.Arguments; -public class SuppliedArgumentSpecificationsFactory : ISuppliedArgumentSpecificationsFactory +public class SuppliedArgumentSpecificationsFactory(IArgumentSpecificationCompatibilityTester argumentSpecificationCompatTester) : ISuppliedArgumentSpecificationsFactory { - private readonly IArgumentSpecificationCompatibilityTester _argumentSpecificationCompatTester; - - public SuppliedArgumentSpecificationsFactory(IArgumentSpecificationCompatibilityTester argumentSpecificationCompatTester) - { - _argumentSpecificationCompatTester = argumentSpecificationCompatTester; - } - public ISuppliedArgumentSpecifications Create(IEnumerable argumentSpecifications) { - return new SuppliedArgumentSpecifications(_argumentSpecificationCompatTester, argumentSpecifications); + return new SuppliedArgumentSpecifications(argumentSpecificationCompatTester, argumentSpecifications); } } \ No newline at end of file diff --git a/src/NSubstitute/Core/CallActions.cs b/src/NSubstitute/Core/CallActions.cs index f0a3821b..1888df5a 100644 --- a/src/NSubstitute/Core/CallActions.cs +++ b/src/NSubstitute/Core/CallActions.cs @@ -2,11 +2,10 @@ namespace NSubstitute.Core; -public class CallActions : ICallActions +public class CallActions(ICallInfoFactory callInfoFactory) : ICallActions { private static readonly Action EmptyAction = x => { }; - private readonly ICallInfoFactory _callInfoFactory; // Collection consideration. // We need to have a thread-safe collection which should be enumerated in add order. // Even though Queue allocates on each enumeration, we expect callbacks to occur rarely, @@ -14,11 +13,6 @@ public class CallActions : ICallActions // If we want to optimize it later, we should probably take a look at System.Collections.Immutable. private ConcurrentQueue _actions = new(); - public CallActions(ICallInfoFactory callInfoFactory) - { - _callInfoFactory = callInfoFactory; - } - public void Add(ICallSpecification callSpecification, Action action) { _actions.Enqueue(new CallAction(callSpecification, action)); @@ -61,30 +55,22 @@ public void InvokeMatchingActions(ICall call) continue; // Optimization. Initialize call lazily, as most of times there are no callbacks. - callInfo ??= _callInfoFactory.Create(call); + callInfo ??= callInfoFactory.Create(call); action.Invoke(callInfo); } } - private class CallAction + private class CallAction(ICallSpecification callSpecification, Action action) { - public CallAction(ICallSpecification callSpecification, Action action) - { - _callSpecification = callSpecification; - _action = action; - } - - private ICallSpecification _callSpecification; - private readonly Action _action; - public bool IsSatisfiedBy(ICall call) => _callSpecification.IsSatisfiedBy(call); + public bool IsSatisfiedBy(ICall call) => callSpecification.IsSatisfiedBy(call); public void Invoke(CallInfo callInfo) { - _action(callInfo); - _callSpecification.InvokePerArgumentActions(callInfo); + action(callInfo); + callSpecification.InvokePerArgumentActions(callInfo); } - public bool IsFor(ICallSpecification spec) => _callSpecification == spec; - public void UpdateCallSpecification(ICallSpecification spec) => _callSpecification = spec; + public bool IsFor(ICallSpecification spec) => callSpecification == spec; + public void UpdateCallSpecification(ICallSpecification spec) => callSpecification = spec; } } diff --git a/src/NSubstitute/Core/CallBaseConfiguration.cs b/src/NSubstitute/Core/CallBaseConfiguration.cs index d25c7a9e..b96d3328 100644 --- a/src/NSubstitute/Core/CallBaseConfiguration.cs +++ b/src/NSubstitute/Core/CallBaseConfiguration.cs @@ -54,17 +54,10 @@ private bool TryGetExplicitConfiguration(ICall call, out bool callBase) return false; } - private readonly struct CallBaseRule + private readonly struct CallBaseRule(ICallSpecification callSpecification, bool callBase) { - private ICallSpecification CallSpecification { get; } - public bool CallBase { get; } + public bool CallBase { get; } = callBase; - public CallBaseRule(ICallSpecification callSpecification, bool callBase) - { - CallSpecification = callSpecification; - CallBase = callBase; - } - - public bool IsSatisfiedBy(ICall call) => CallSpecification.IsSatisfiedBy(call); + public bool IsSatisfiedBy(ICall call) => callSpecification.IsSatisfiedBy(call); } } \ No newline at end of file diff --git a/src/NSubstitute/Core/CallCollection.cs b/src/NSubstitute/Core/CallCollection.cs index 1c5f4e75..786f296a 100644 --- a/src/NSubstitute/Core/CallCollection.cs +++ b/src/NSubstitute/Core/CallCollection.cs @@ -66,9 +66,9 @@ internal interface IReceivedCallEntry /// That is needed because concurrent collections don't have a Delete method. /// Notice, in most cases the original instance will be used as a wrapper itself. /// - private class ReceivedCallEntry : IReceivedCallEntry + private class ReceivedCallEntry(ICall call) : IReceivedCallEntry { - public ICall? Call { get; private set; } + public ICall? Call { get; private set; } = call; [MemberNotNullWhen(false, nameof(Call))] public bool IsSkipped => Call == null; @@ -77,10 +77,5 @@ private class ReceivedCallEntry : IReceivedCallEntry public bool TryTakeEntryOwnership() => throw new SubstituteInternalException("Ownership is never expected to be obtained for this entry."); - - public ReceivedCallEntry(ICall call) - { - Call = call; - } } } \ No newline at end of file diff --git a/src/NSubstitute/Core/CallInfo.cs b/src/NSubstitute/Core/CallInfo.cs index cd543855..63ac178e 100644 --- a/src/NSubstitute/Core/CallInfo.cs +++ b/src/NSubstitute/Core/CallInfo.cs @@ -6,14 +6,8 @@ namespace NSubstitute.Core; -public class CallInfo +public class CallInfo(Argument[] callArguments) { - private readonly Argument[] _callArguments; - - public CallInfo(Argument[] callArguments) - { - _callArguments = callArguments; - } /// /// Gets the nth argument to this call. @@ -22,10 +16,10 @@ public CallInfo(Argument[] callArguments) /// The value of the argument at the given index public object this[int index] { - get => _callArguments[index].Value; + get => callArguments[index].Value; set { - var argument = _callArguments[index]; + var argument = callArguments[index]; EnsureArgIsSettable(argument, index, value); argument.Value = value; } @@ -48,13 +42,13 @@ private void EnsureArgIsSettable(Argument argument, int index, object value) /// Get the arguments passed to this call. /// /// Array of all arguments passed to this call - public object[] Args() => _callArguments.Select(x => x.Value).ToArray(); + public object[] Args() => callArguments.Select(x => x.Value).ToArray(); /// /// Gets the types of all the arguments passed to this call. /// /// Array of types of all arguments passed to this call - public Type[] ArgTypes() => _callArguments.Select(x => x.DeclaredType).ToArray(); + public Type[] ArgTypes() => callArguments.Select(x => x.DeclaredType).ToArray(); /// /// Gets the argument of type `T` passed to this call. This will throw if there are no arguments @@ -74,7 +68,7 @@ private bool TryGetArg(Func condition, [MaybeNullWhen(false)] { value = default; - var matchingArgs = _callArguments.Where(condition); + var matchingArgs = callArguments.Where(condition); if (!matchingArgs.Any()) return false; ThrowIfMoreThanOne(matchingArgs); @@ -89,7 +83,7 @@ private void ThrowIfMoreThanOne(IEnumerable arguments) throw new AmbiguousArgumentsException( "There is more than one argument of type " + typeof(T).FullName + " to this call.\n" + "The call signature is (" + DisplayTypes(ArgTypes()) + ")\n" + - " and was called with (" + DisplayTypes(_callArguments.Select(x => x.ActualType)) + ")" + " and was called with (" + DisplayTypes(callArguments.Select(x => x.ActualType)) + ")" ); } } @@ -104,14 +98,14 @@ private void ThrowIfMoreThanOne(IEnumerable arguments) /// The argument passed to the call, or throws if there is not exactly one argument of this type public T ArgAt(int position) { - if (position >= _callArguments.Length) + if (position >= callArguments.Length) { throw new ArgumentOutOfRangeException(nameof(position), $"There is no argument at position {position}"); } try { - return (T)_callArguments[position].Value!; + return (T)callArguments[position].Value!; } catch (InvalidCastException) { diff --git a/src/NSubstitute/Core/CallResults.cs b/src/NSubstitute/Core/CallResults.cs index becab0bb..a13ed1dc 100644 --- a/src/NSubstitute/Core/CallResults.cs +++ b/src/NSubstitute/Core/CallResults.cs @@ -2,19 +2,12 @@ namespace NSubstitute.Core; -public class CallResults : ICallResults +public class CallResults(ICallInfoFactory callInfoFactory) : ICallResults { - private readonly ICallInfoFactory _callInfoFactory; // There was made a decision to use ConcurrentStack instead of ConcurrentQueue here. // The pros is that reverse enumeration is cheap. The cons is that stack allocates on each push. // We presume that read operations will dominate, so stack suits better. - private readonly ConcurrentStack _results; - - public CallResults(ICallInfoFactory callInfoFactory) - { - _results = new ConcurrentStack(); - _callInfoFactory = callInfoFactory; - } + private readonly ConcurrentStack _results = new ConcurrentStack(); public void SetResult(ICallSpecification callSpecification, IReturn result) { @@ -34,7 +27,7 @@ public bool TryGetResult(ICall call, out object? result) return false; } - result = configuredResult.GetResult(call, _callInfoFactory); + result = configuredResult.GetResult(call, callInfoFactory); return true; } @@ -70,27 +63,18 @@ private static bool ReturnsVoidFrom(ICall call) return call.GetReturnType() == typeof(void); } - private readonly struct ResultForCallSpec + private readonly struct ResultForCallSpec(ICallSpecification callSpecification, IReturn resultToReturn) { - private readonly ICallSpecification _callSpecification; - private readonly IReturn _resultToReturn; - - public ResultForCallSpec(ICallSpecification callSpecification, IReturn resultToReturn) - { - _callSpecification = callSpecification; - _resultToReturn = resultToReturn; - } - - public bool IsResultFor(ICall call) => _callSpecification.IsSatisfiedBy(call); + public bool IsResultFor(ICall call) => callSpecification.IsSatisfiedBy(call); public object? GetResult(ICall call, ICallInfoFactory callInfoFactory) { - if (_resultToReturn is ICallIndependentReturn callIndependentReturn) + if (resultToReturn is ICallIndependentReturn callIndependentReturn) { return callIndependentReturn.GetReturnValue(); } var callInfo = callInfoFactory.Create(call); - return _resultToReturn.ReturnFor(callInfo); + return resultToReturn.ReturnFor(callInfo); } } } \ No newline at end of file diff --git a/src/NSubstitute/Core/CallRouter.cs b/src/NSubstitute/Core/CallRouter.cs index 05bba69a..45201a5f 100644 --- a/src/NSubstitute/Core/CallRouter.cs +++ b/src/NSubstitute/Core/CallRouter.cs @@ -3,29 +3,20 @@ namespace NSubstitute.Core; -public class CallRouter : ICallRouter +public class CallRouter( + ISubstituteState substituteState, + IThreadLocalContext threadContext, + IRouteFactory routeFactory, + bool canConfigureBaseCalls) : ICallRouter { - private readonly ISubstituteState _substituteState; - private readonly IThreadLocalContext _threadContext; - private readonly IRouteFactory _routeFactory; - private readonly bool _canConfigureBaseCalls; - - public CallRouter(ISubstituteState substituteState, IThreadLocalContext threadContext, IRouteFactory routeFactory, bool canConfigureBaseCalls) - { - _substituteState = substituteState; - _threadContext = threadContext; - _routeFactory = routeFactory; - _canConfigureBaseCalls = canConfigureBaseCalls; - } - public bool CallBaseByDefault { - get => _substituteState.CallBaseConfiguration.CallBaseByDefault; + get => substituteState.CallBaseConfiguration.CallBaseByDefault; set { - if (!_canConfigureBaseCalls) throw CouldNotConfigureCallBaseException.ForAllCalls(); + if (!canConfigureBaseCalls) throw CouldNotConfigureCallBaseException.ForAllCalls(); - _substituteState.CallBaseConfiguration.CallBaseByDefault = value; + substituteState.CallBaseConfiguration.CallBaseByDefault = value; } } @@ -33,34 +24,34 @@ public void Clear(ClearOptions options) { if ((options & ClearOptions.CallActions) == ClearOptions.CallActions) { - _substituteState.CallActions.Clear(); + substituteState.CallActions.Clear(); } if ((options & ClearOptions.ReturnValues) == ClearOptions.ReturnValues) { - _substituteState.CallResults.Clear(); - _substituteState.ResultsForType.Clear(); + substituteState.CallResults.Clear(); + substituteState.ResultsForType.Clear(); } if ((options & ClearOptions.ReceivedCalls) == ClearOptions.ReceivedCalls) { - _substituteState.ReceivedCalls.Clear(); + substituteState.ReceivedCalls.Clear(); } } public IEnumerable ReceivedCalls() { - return _substituteState.ReceivedCalls.AllCalls(); + return substituteState.ReceivedCalls.AllCalls(); } public void SetRoute(Func getRoute) => - _threadContext.SetNextRoute(this, getRoute); + threadContext.SetNextRoute(this, getRoute); public object? Route(ICall call) { - _threadContext.SetLastCallRouter(this); + threadContext.SetLastCallRouter(this); - var isQuerying = _threadContext.IsQuerying; - var pendingRaisingEventArgs = _threadContext.UsePendingRaisingEventArgumentsFactory(); - var queuedNextRouteFactory = _threadContext.UseNextRoute(this); + var isQuerying = threadContext.IsQuerying; + var pendingRaisingEventArgs = threadContext.UsePendingRaisingEventArgumentsFactory(); + var queuedNextRouteFactory = threadContext.UseNextRoute(this); IRoute routeToUse = ResolveCurrentRoute(call, isQuerying, pendingRaisingEventArgs, queuedNextRouteFactory); @@ -71,25 +62,25 @@ private IRoute ResolveCurrentRoute(ICall call, bool isQuerying, Func argumentSpecifications) : ICallSpecification { - private readonly MethodInfo _methodInfo; - private readonly IArgumentSpecification[] _argumentSpecifications; + private readonly IArgumentSpecification[] _argumentSpecifications = argumentSpecifications.ToArray(); - public CallSpecification(MethodInfo methodInfo, IEnumerable argumentSpecifications) - { - _methodInfo = methodInfo; - _argumentSpecifications = argumentSpecifications.ToArray(); - } - - public MethodInfo GetMethodInfo() => _methodInfo; + public MethodInfo GetMethodInfo() => methodInfo; - public Type ReturnType() => _methodInfo.ReturnType; + public Type ReturnType() => methodInfo.ReturnType; public bool IsSatisfiedBy(ICall call) { diff --git a/src/NSubstitute/Core/CallSpecificationFactory.cs b/src/NSubstitute/Core/CallSpecificationFactory.cs index d37e8e52..7f213859 100644 --- a/src/NSubstitute/Core/CallSpecificationFactory.cs +++ b/src/NSubstitute/Core/CallSpecificationFactory.cs @@ -2,22 +2,15 @@ namespace NSubstitute.Core; -public class CallSpecificationFactory : ICallSpecificationFactory +public class CallSpecificationFactory(IArgumentSpecificationsFactory argumentSpecificationsFactory) : ICallSpecificationFactory { - private readonly IArgumentSpecificationsFactory _argumentSpecificationsFactory; - - public CallSpecificationFactory(IArgumentSpecificationsFactory argumentSpecificationsFactory) - { - _argumentSpecificationsFactory = argumentSpecificationsFactory; - } - public ICallSpecification CreateFrom(ICall call, MatchArgs matchArgs) { var methodInfo = call.GetMethodInfo(); var argumentSpecs = call.GetArgumentSpecifications(); var arguments = call.GetOriginalArguments(); var parameterInfos = call.GetParameterInfos(); - var argumentSpecificationsForCall = _argumentSpecificationsFactory.Create(argumentSpecs, arguments, parameterInfos, methodInfo, matchArgs); + var argumentSpecificationsForCall = argumentSpecificationsFactory.Create(argumentSpecs, arguments, parameterInfos, methodInfo, matchArgs); return new CallSpecification(methodInfo, argumentSpecificationsForCall); } } diff --git a/src/NSubstitute/Core/ConfigureCall.cs b/src/NSubstitute/Core/ConfigureCall.cs index 7ea684d1..0e7152b1 100644 --- a/src/NSubstitute/Core/ConfigureCall.cs +++ b/src/NSubstitute/Core/ConfigureCall.cs @@ -2,32 +2,21 @@ namespace NSubstitute.Core; -public class ConfigureCall : IConfigureCall +public class ConfigureCall(ICallResults configuredResults, ICallActions callActions, IGetCallSpec getCallSpec) : IConfigureCall { - private readonly ICallResults _configuredResults; - private readonly ICallActions _callActions; - private readonly IGetCallSpec _getCallSpec; - - public ConfigureCall(ICallResults configuredResults, ICallActions callActions, IGetCallSpec getCallSpec) - { - _configuredResults = configuredResults; - _callActions = callActions; - _getCallSpec = getCallSpec; - } - public ConfiguredCall SetResultForLastCall(IReturn valueToReturn, MatchArgs matchArgs, PendingSpecificationInfo pendingSpecInfo) { - var spec = _getCallSpec.FromPendingSpecification(matchArgs, pendingSpecInfo); + var spec = getCallSpec.FromPendingSpecification(matchArgs, pendingSpecInfo); CheckResultIsCompatibleWithCall(valueToReturn, spec); - _configuredResults.SetResult(spec, valueToReturn); - return new ConfiguredCall(action => _callActions.Add(spec, action)); + configuredResults.SetResult(spec, valueToReturn); + return new ConfiguredCall(action => callActions.Add(spec, action)); } public void SetResultForCall(ICall call, IReturn valueToReturn, MatchArgs matchArgs) { - var spec = _getCallSpec.FromCall(call, matchArgs); + var spec = getCallSpec.FromCall(call, matchArgs); CheckResultIsCompatibleWithCall(valueToReturn, spec); - _configuredResults.SetResult(spec, valueToReturn); + configuredResults.SetResult(spec, valueToReturn); } private static void CheckResultIsCompatibleWithCall(IReturn valueToReturn, ICallSpecification spec) diff --git a/src/NSubstitute/Core/ConfiguredCall.cs b/src/NSubstitute/Core/ConfiguredCall.cs index ebc6ad5b..46a3d3bf 100644 --- a/src/NSubstitute/Core/ConfiguredCall.cs +++ b/src/NSubstitute/Core/ConfiguredCall.cs @@ -3,14 +3,8 @@ namespace NSubstitute.Core; -public class ConfiguredCall +public class ConfiguredCall(Action> addAction) { - private readonly Action> _addAction; - - public ConfiguredCall(Action> addAction) - { - _addAction = addAction; - } /// /// Adds a callback to execute for matching calls. @@ -19,7 +13,7 @@ public ConfiguredCall(Action> addAction) /// public ConfiguredCall AndDoes(Action action) { - _addAction(action); + addAction(action); return this; } } \ No newline at end of file diff --git a/src/NSubstitute/Core/CustomHandlers.cs b/src/NSubstitute/Core/CustomHandlers.cs index 3712e9ba..617a05b8 100644 --- a/src/NSubstitute/Core/CustomHandlers.cs +++ b/src/NSubstitute/Core/CustomHandlers.cs @@ -1,19 +1,13 @@ namespace NSubstitute.Core; -public class CustomHandlers : ICustomHandlers +public class CustomHandlers(ISubstituteState substituteState) : ICustomHandlers { private readonly List _handlers = []; - private readonly ISubstituteState _substituteState; public IReadOnlyCollection Handlers => _handlers; - public CustomHandlers(ISubstituteState substituteState) - { - _substituteState = substituteState; - } - public void AddCustomHandlerFactory(CallHandlerFactory factory) { - _handlers.Add(factory.Invoke(_substituteState)); + _handlers.Add(factory.Invoke(substituteState)); } } \ No newline at end of file diff --git a/src/NSubstitute/Core/DependencyInjection/NSubContainer.cs b/src/NSubstitute/Core/DependencyInjection/NSubContainer.cs index 0daa91c2..db90cccf 100644 --- a/src/NSubstitute/Core/DependencyInjection/NSubContainer.cs +++ b/src/NSubstitute/Core/DependencyInjection/NSubContainer.cs @@ -137,27 +137,20 @@ private void SetRegistration(Type type, Registration registration) } } - private class Registration + private class Registration(Func factory, NSubLifetime lifetime) { - private readonly Func _factory; private object? _singletonValue; - public NSubLifetime Lifetime { get; } - - public Registration(Func factory, NSubLifetime lifetime) - { - _factory = factory; - Lifetime = lifetime; - } + public NSubLifetime Lifetime { get; } = lifetime; public object Resolve(Scope scope) { switch (Lifetime) { case NSubLifetime.Transient: - return _factory.Invoke(scope); + return factory.Invoke(scope); case NSubLifetime.Singleton: - return _singletonValue ??= _factory.Invoke(scope); + return _singletonValue ??= factory.Invoke(scope); case NSubLifetime.PerScope: if (scope.TryGetCached(this, out var result)) @@ -165,7 +158,7 @@ public object Resolve(Scope scope) return result; } - result = _factory.Invoke(scope); + result = factory.Invoke(scope); scope.Set(this, result); return result; @@ -175,15 +168,9 @@ public object Resolve(Scope scope) } } - private class Scope : INSubResolver + private class Scope(NSubContainer mostNestedContainer) : INSubResolver { private readonly Dictionary _cache = []; - private readonly NSubContainer _mostNestedContainer; - - public Scope(NSubContainer mostNestedContainer) - { - _mostNestedContainer = mostNestedContainer; - } public T Resolve() where T : notnull => (T)Resolve(typeof(T)); @@ -201,9 +188,9 @@ public object Resolve(Type type) { // The same lock object is shared among all the nested containers, // so we synchronize across the whole containers graph. - lock (_mostNestedContainer._syncRoot) + lock (mostNestedContainer._syncRoot) { - Registration? registration = _mostNestedContainer.TryFindRegistration(type); + Registration? registration = mostNestedContainer.TryFindRegistration(type); if (registration == null) throw new InvalidOperationException($"Type is not registered: {type.FullName}"); @@ -215,7 +202,7 @@ public object Resolve(Registration registration) { // The same lock object is shared among all the nested containers, // so we synchronize across the whole containers graph. - lock (_mostNestedContainer._syncRoot) + lock (mostNestedContainer._syncRoot) { return registration.Resolve(this); } diff --git a/src/NSubstitute/Core/EventCallFormatter.cs b/src/NSubstitute/Core/EventCallFormatter.cs index 6494ce4f..572ac431 100644 --- a/src/NSubstitute/Core/EventCallFormatter.cs +++ b/src/NSubstitute/Core/EventCallFormatter.cs @@ -2,30 +2,22 @@ namespace NSubstitute.Core; -public class EventCallFormatter : IMethodInfoFormatter +public class EventCallFormatter(Func> eventsToFormat) : IMethodInfoFormatter { public static readonly Func> IsSubscription = call => (eventInfo => eventInfo.GetAddMethod() == call); public static readonly Func> IsUnsubscription = call => (eventInfo => eventInfo.GetRemoveMethod() == call); - - private readonly Func> _eventsToFormat; - private readonly string _eventOperator; - - public EventCallFormatter(Func> eventsToFormat) - { - _eventsToFormat = eventsToFormat; - _eventOperator = eventsToFormat == IsSubscription ? "+=" : "-="; - } + private readonly string _eventOperator = eventsToFormat == IsSubscription ? "+=" : "-="; public bool CanFormat(MethodInfo methodInfo) { - return methodInfo.DeclaringType!.GetEvents().Any(x => _eventsToFormat(methodInfo)(x)); + return methodInfo.DeclaringType!.GetEvents().Any(x => eventsToFormat(methodInfo)(x)); } public string Format(MethodInfo methodInfo, IEnumerable arguments) { - var eventInfo = methodInfo.DeclaringType!.GetEvents().First(x => _eventsToFormat(methodInfo)(x)); + var eventInfo = methodInfo.DeclaringType!.GetEvents().First(x => eventsToFormat(methodInfo)(x)); return Format(eventInfo, _eventOperator, arguments); } diff --git a/src/NSubstitute/Core/Events/DelegateEventWrapper.cs b/src/NSubstitute/Core/Events/DelegateEventWrapper.cs index b45308e6..47ebda00 100644 --- a/src/NSubstitute/Core/Events/DelegateEventWrapper.cs +++ b/src/NSubstitute/Core/Events/DelegateEventWrapper.cs @@ -2,16 +2,10 @@ namespace NSubstitute.Core.Events; -public class DelegateEventWrapper : RaiseEventWrapper +public class DelegateEventWrapper(params object?[] arguments) : RaiseEventWrapper { - private readonly object?[] _providedArguments; protected override string RaiseMethodName => "Raise.Event"; - public DelegateEventWrapper(params object?[] arguments) - { - _providedArguments = arguments; - } - // Disable nullability for client API, so it does not affect clients. #nullable disable annotations public static implicit operator T(DelegateEventWrapper wrapper) @@ -25,17 +19,17 @@ public static implicit operator T(DelegateEventWrapper wrapper) { var requiredArgs = typeof(T).GetInvokeMethod().GetParameters(); - if (_providedArguments.Length < 2 && LooksLikeAnEventStyleCall(requiredArgs)) + if (arguments.Length < 2 && LooksLikeAnEventStyleCall(requiredArgs)) { return WorkOutSenderAndEventArgs(requiredArgs[1].ParameterType, call); } - if (!RequiredArgsHaveBeenProvided(_providedArguments, requiredArgs)) + if (!RequiredArgsHaveBeenProvided(arguments, requiredArgs)) { ThrowBecauseRequiredArgsNotProvided(requiredArgs); } - return _providedArguments; + return arguments; } private bool LooksLikeAnEventStyleCall(ParameterInfo[] parameters) @@ -49,19 +43,19 @@ private bool LooksLikeAnEventStyleCall(ParameterInfo[] parameters) { object? sender; object? eventArgs; - if (_providedArguments.Length == 0) + if (arguments.Length == 0) { sender = call.Target(); eventArgs = GetDefaultForEventArgType(eventArgsType); } - else if (_providedArguments[0].IsCompatibleWith(eventArgsType)) + else if (arguments[0].IsCompatibleWith(eventArgsType)) { sender = call.Target(); - eventArgs = _providedArguments[0]; + eventArgs = arguments[0]; } else { - sender = _providedArguments[0]; + sender = arguments[0]; eventArgs = GetDefaultForEventArgType(eventArgsType); } return [sender, eventArgs]; diff --git a/src/NSubstitute/Core/Events/EventHandlerWrapper.cs b/src/NSubstitute/Core/Events/EventHandlerWrapper.cs index 29d4f599..f4055d14 100644 --- a/src/NSubstitute/Core/Events/EventHandlerWrapper.cs +++ b/src/NSubstitute/Core/Events/EventHandlerWrapper.cs @@ -1,21 +1,15 @@ namespace NSubstitute.Core.Events; -public class EventHandlerWrapper : RaiseEventWrapper where TEventArgs : EventArgs +public class EventHandlerWrapper(object? sender, EventArgs? eventArgs) : RaiseEventWrapper where TEventArgs : EventArgs { - private readonly object? _sender; - private readonly EventArgs? _eventArgs; + private readonly object? _sender = sender; + private readonly EventArgs? _eventArgs = eventArgs; protected override string RaiseMethodName => "Raise.EventWith"; public EventHandlerWrapper() : this(null, null) { } public EventHandlerWrapper(EventArgs? eventArgs) : this(null, eventArgs) { } - public EventHandlerWrapper(object? sender, EventArgs? eventArgs) - { - _sender = sender; - _eventArgs = eventArgs; - } - // Disable nullability for client API, so it does not affect clients. #nullable disable annotations public static implicit operator EventHandler(EventHandlerWrapper wrapper) diff --git a/src/NSubstitute/Core/GetCallSpec.cs b/src/NSubstitute/Core/GetCallSpec.cs index 4e42d8ec..4bb7a0f5 100644 --- a/src/NSubstitute/Core/GetCallSpec.cs +++ b/src/NSubstitute/Core/GetCallSpec.cs @@ -1,32 +1,24 @@ namespace NSubstitute.Core; -public class GetCallSpec : IGetCallSpec +public class GetCallSpec( + ICallCollection receivedCalls, + ICallSpecificationFactory callSpecificationFactory, + ICallActions callActions) : IGetCallSpec { - private readonly ICallCollection _receivedCalls; - private readonly ICallSpecificationFactory _callSpecificationFactory; - private readonly ICallActions _callActions; - - public GetCallSpec(ICallCollection receivedCalls, ICallSpecificationFactory callSpecificationFactory, ICallActions callActions) - { - _receivedCalls = receivedCalls; - _callSpecificationFactory = callSpecificationFactory; - _callActions = callActions; - } - public ICallSpecification FromPendingSpecification(MatchArgs matchArgs, PendingSpecificationInfo pendingSpecInfo) { return pendingSpecInfo.Handle( callSpec => FromExistingSpec(callSpec, matchArgs), lastCall => { - _receivedCalls.Delete(lastCall); + receivedCalls.Delete(lastCall); return FromCall(lastCall, matchArgs); }); } public ICallSpecification FromCall(ICall call, MatchArgs matchArgs) { - return _callSpecificationFactory.CreateFrom(call, matchArgs); + return callSpecificationFactory.CreateFrom(call, matchArgs); } public ICallSpecification FromExistingSpec(ICallSpecification spec, MatchArgs matchArgs) @@ -37,7 +29,7 @@ public ICallSpecification FromExistingSpec(ICallSpecification spec, MatchArgs ma private ICallSpecification UpdateCallSpecToMatchAnyArgs(ICallSpecification callSpecification) { var anyArgCallSpec = callSpecification.CreateCopyThatMatchesAnyArguments(); - _callActions.MoveActionsForSpecToNewSpec(callSpecification, anyArgCallSpec); + callActions.MoveActionsForSpecToNewSpec(callSpecification, anyArgCallSpec); return anyArgCallSpec; } } \ No newline at end of file diff --git a/src/NSubstitute/Core/IReturn.cs b/src/NSubstitute/Core/IReturn.cs index 8d60c9e1..92cfd56b 100644 --- a/src/NSubstitute/Core/IReturn.cs +++ b/src/NSubstitute/Core/IReturn.cs @@ -19,29 +19,17 @@ internal interface ICallIndependentReturn object? GetReturnValue(); } -public class ReturnValue : IReturn, ICallIndependentReturn +public class ReturnValue(object? value) : IReturn, ICallIndependentReturn { - private readonly object? _value; - - public ReturnValue(object? value) - { - _value = value; - } - - public object? GetReturnValue() => _value; + public object? GetReturnValue() => value; public object? ReturnFor(CallInfo info) => GetReturnValue(); - public Type? TypeOrNull() => _value?.GetType(); - public bool CanBeAssignedTo(Type t) => _value.IsCompatibleWith(t); + public Type? TypeOrNull() => value?.GetType(); + public bool CanBeAssignedTo(Type t) => value.IsCompatibleWith(t); } -public class ReturnValueFromFunc : IReturn +public class ReturnValueFromFunc(Func? funcToReturnValue) : IReturn { - private readonly Func _funcToReturnValue; - - public ReturnValueFromFunc(Func? funcToReturnValue) - { - _funcToReturnValue = funcToReturnValue ?? ReturnNull(); - } + private readonly Func _funcToReturnValue = funcToReturnValue ?? ReturnNull(); public object? ReturnFor(CallInfo info) => _funcToReturnValue(info); public Type TypeOrNull() => typeof(T); @@ -54,16 +42,10 @@ public ReturnValueFromFunc(Func? funcToReturnValue) } } -public class ReturnMultipleValues : IReturn, ICallIndependentReturn +public class ReturnMultipleValues(T?[] values) : IReturn, ICallIndependentReturn { - private readonly ConcurrentQueue _valuesToReturn; - private readonly T? _lastValue; - - public ReturnMultipleValues(T?[] values) - { - _valuesToReturn = new ConcurrentQueue(values); - _lastValue = values.Last(); - } + private readonly ConcurrentQueue _valuesToReturn = new ConcurrentQueue(values); + private readonly T? _lastValue = values.Last(); public object? GetReturnValue() => GetNext(); public object? ReturnFor(CallInfo info) => GetReturnValue(); @@ -73,16 +55,10 @@ public ReturnMultipleValues(T?[] values) private T? GetNext() => _valuesToReturn.TryDequeue(out var nextResult) ? nextResult : _lastValue; } -public class ReturnMultipleFuncsValues : IReturn +public class ReturnMultipleFuncsValues(Func[] funcs) : IReturn { - private readonly ConcurrentQueue> _funcsToReturn; - private readonly Func _lastFunc; - - public ReturnMultipleFuncsValues(Func[] funcs) - { - _funcsToReturn = new ConcurrentQueue>(funcs); - _lastFunc = funcs.Last(); - } + private readonly ConcurrentQueue> _funcsToReturn = new ConcurrentQueue>(funcs); + private readonly Func _lastFunc = funcs.Last(); public object? ReturnFor(CallInfo info) => GetNext(info); public Type TypeOrNull() => typeof(T); diff --git a/src/NSubstitute/Core/ParameterInfoWrapper.cs b/src/NSubstitute/Core/ParameterInfoWrapper.cs index a6857a17..cec9a05b 100644 --- a/src/NSubstitute/Core/ParameterInfoWrapper.cs +++ b/src/NSubstitute/Core/ParameterInfoWrapper.cs @@ -2,20 +2,13 @@ namespace NSubstitute.Core; -internal class ParameterInfoWrapper : IParameterInfo +internal class ParameterInfoWrapper(ParameterInfo parameterInfo) : IParameterInfo { - private readonly ParameterInfo _parameterInfo; + public Type ParameterType => parameterInfo.ParameterType; - public ParameterInfoWrapper(ParameterInfo parameterInfo) - { - _parameterInfo = parameterInfo; - } + public bool IsParams => parameterInfo.IsParams(); - public Type ParameterType => _parameterInfo.ParameterType; + public bool IsOptional => parameterInfo.IsOptional; - public bool IsParams => _parameterInfo.IsParams(); - - public bool IsOptional => _parameterInfo.IsOptional; - - public bool IsOut => _parameterInfo.IsOut; + public bool IsOut => parameterInfo.IsOut; } \ No newline at end of file diff --git a/src/NSubstitute/Core/PropertyHelper.cs b/src/NSubstitute/Core/PropertyHelper.cs index 44f701d4..2087df54 100644 --- a/src/NSubstitute/Core/PropertyHelper.cs +++ b/src/NSubstitute/Core/PropertyHelper.cs @@ -5,17 +5,8 @@ namespace NSubstitute.Core; -public class PropertyHelper : IPropertyHelper +public class PropertyHelper(ICallFactory callFactory, IArgumentSpecificationCompatibilityTester argSpecCompatTester) : IPropertyHelper { - private readonly ICallFactory _callFactory; - private readonly IArgumentSpecificationCompatibilityTester _argSpecCompatTester; - - public PropertyHelper(ICallFactory callFactory, IArgumentSpecificationCompatibilityTester argSpecCompatTester) - { - _callFactory = callFactory; - _argSpecCompatTester = argSpecCompatTester; - } - public bool IsCallToSetAReadWriteProperty(ICall call) { var propertySetter = GetPropertyFromSetterCall(call); @@ -46,7 +37,7 @@ public ICall CreateCallToPropertyGetterFromSetterCall(ICall callToSetter) var getterArgs = SkipLast(callToSetter.GetOriginalArguments()); var getterArgumentSpecifications = GetGetterCallSpecificationsFromSetterCall(callToSetter); - return _callFactory.Create(getter, getterArgs, callToSetter.Target(), getterArgumentSpecifications); + return callFactory.Create(getter, getterArgs, callToSetter.Target(), getterArgumentSpecifications); } private IList GetGetterCallSpecificationsFromSetterCall(ICall callToSetter) @@ -62,7 +53,7 @@ private IList GetGetterCallSpecificationsFromSetterCall( // Therefore, we need to remove the last argument specification if it's for the trimmed arg. // Otherwise, NSubstitute might find that the redundant argument specification is present and the // validation logic might trigger an exception. - if (_argSpecCompatTester.IsSpecificationCompatible(argumentSpecifications.Last(), lastSetterArg, lastSetterArgType)) + if (argSpecCompatTester.IsSpecificationCompatible(argumentSpecifications.Last(), lastSetterArg, lastSetterArgType)) { argumentSpecifications = SkipLast(argumentSpecifications); } diff --git a/src/NSubstitute/Core/Query.cs b/src/NSubstitute/Core/Query.cs index bc523f8e..dbfc60b5 100644 --- a/src/NSubstitute/Core/Query.cs +++ b/src/NSubstitute/Core/Query.cs @@ -1,20 +1,14 @@ namespace NSubstitute.Core; -public class Query : IQuery, IQueryResults +public class Query(ICallSpecificationFactory callSpecificationFactory) : IQuery, IQueryResults { private readonly List _querySpec = []; private readonly HashSet _matchingCalls = new(new CallSequenceNumberComparer()); - private readonly ICallSpecificationFactory _callSpecificationFactory; - - public Query(ICallSpecificationFactory callSpecificationFactory) - { - _callSpecificationFactory = callSpecificationFactory; - } public void RegisterCall(ICall call) { var target = call.Target(); - var callSpecification = _callSpecificationFactory.CreateFrom(call, MatchArgs.AsSpecifiedInCall); + var callSpecification = callSpecificationFactory.CreateFrom(call, MatchArgs.AsSpecifiedInCall); _querySpec.Add(new CallSpecAndTarget(callSpecification, target)); diff --git a/src/NSubstitute/Core/ResultsForType.cs b/src/NSubstitute/Core/ResultsForType.cs index 63b4aea5..afbd26c1 100644 --- a/src/NSubstitute/Core/ResultsForType.cs +++ b/src/NSubstitute/Core/ResultsForType.cs @@ -3,14 +3,9 @@ namespace NSubstitute.Core; -public class ResultsForType : IResultsForType +public class ResultsForType(ICallInfoFactory callInfoFactory) : IResultsForType { - private readonly CallResults _results; - - public ResultsForType(ICallInfoFactory callInfoFactory) - { - _results = new CallResults(callInfoFactory); - } + private readonly CallResults _results = new CallResults(callInfoFactory); public void SetResult(Type type, IReturn resultToReturn) { @@ -27,17 +22,10 @@ public void Clear() _results.Clear(); } - private class MatchingReturnTypeSpecification : ICallSpecification + private class MatchingReturnTypeSpecification(Type expectedReturnType) : ICallSpecification { - private readonly Type _expectedReturnType; - - public MatchingReturnTypeSpecification(Type expectedReturnType) - { - _expectedReturnType = expectedReturnType; - } - public bool IsSatisfiedBy(ICall call) - => call.GetReturnType() == _expectedReturnType; + => call.GetReturnType() == expectedReturnType; // ******* Rest methods are not required ******* diff --git a/src/NSubstitute/Core/ReturnObservable.cs b/src/NSubstitute/Core/ReturnObservable.cs index ce023e04..7f3cbb1c 100644 --- a/src/NSubstitute/Core/ReturnObservable.cs +++ b/src/NSubstitute/Core/ReturnObservable.cs @@ -1,19 +1,12 @@ namespace NSubstitute.Core; -internal class ReturnObservable : IObservable +internal class ReturnObservable(T? value) : IObservable { - private readonly T? _value; - public ReturnObservable() : this(default) { } - public ReturnObservable(T? value) - { - _value = value; - } - public IDisposable Subscribe(IObserver observer) { - observer.OnNext(_value); + observer.OnNext(value); observer.OnCompleted(); return EmptyDisposable.Instance; diff --git a/src/NSubstitute/Core/RouteFactoryCacheWrapper.cs b/src/NSubstitute/Core/RouteFactoryCacheWrapper.cs index 808958e4..3118b033 100644 --- a/src/NSubstitute/Core/RouteFactoryCacheWrapper.cs +++ b/src/NSubstitute/Core/RouteFactoryCacheWrapper.cs @@ -3,24 +3,17 @@ namespace NSubstitute.Core; -public class RouteFactoryCacheWrapper : IRouteFactory +public class RouteFactoryCacheWrapper(IRouteFactory factory) : IRouteFactory { - private readonly IRouteFactory _factory; - private CachedRoute _recordReplayCache; private CachedRoute _recordCallSpecificationCache; - public RouteFactoryCacheWrapper(IRouteFactory factory) - { - _factory = factory; - } - public IRoute RecordReplay(ISubstituteState state) { // Don't care about concurrency - routes are immutable and in worst case we'll simply create a few ones. if (_recordReplayCache.State != state) { - _recordReplayCache = new CachedRoute(_factory.RecordReplay(state), state); + _recordReplayCache = new CachedRoute(factory.RecordReplay(state), state); } return _recordReplayCache.Route; @@ -31,39 +24,33 @@ public IRoute RecordCallSpecification(ISubstituteState state) // Don't care about concurrency - routes are immutable and in worst case we'll simply create a few ones. if (_recordCallSpecificationCache.State != state) { - _recordCallSpecificationCache = new CachedRoute(_factory.RecordCallSpecification(state), state); + _recordCallSpecificationCache = new CachedRoute(factory.RecordCallSpecification(state), state); } return _recordCallSpecificationCache.Route; } public IRoute CallQuery(ISubstituteState state) => - _factory.CallQuery(state); + factory.CallQuery(state); public IRoute CheckReceivedCalls(ISubstituteState state, MatchArgs matchArgs, Quantity requiredQuantity) => - _factory.CheckReceivedCalls(state, matchArgs, requiredQuantity); + factory.CheckReceivedCalls(state, matchArgs, requiredQuantity); public IRoute DoWhenCalled(ISubstituteState state, Action doAction, MatchArgs matchArgs) => - _factory.DoWhenCalled(state, doAction, matchArgs); + factory.DoWhenCalled(state, doAction, matchArgs); public IRoute DoNotCallBase(ISubstituteState state, MatchArgs matchArgs) => - _factory.DoNotCallBase(state, matchArgs); + factory.DoNotCallBase(state, matchArgs); public IRoute CallBase(ISubstituteState state, MatchArgs matchArgs) => - _factory.CallBase(state, matchArgs); + factory.CallBase(state, matchArgs); public IRoute RaiseEvent(ISubstituteState state, Func getEventArguments) => - _factory.RaiseEvent(state, getEventArguments); + factory.RaiseEvent(state, getEventArguments); - private readonly struct CachedRoute + private readonly struct CachedRoute(IRoute route, ISubstituteState state) { - public readonly IRoute Route; - public readonly ISubstituteState State; - - public CachedRoute(IRoute route, ISubstituteState state) - { - Route = route; - State = state; - } + public readonly IRoute Route = route; + public readonly ISubstituteState State = state; } } \ No newline at end of file diff --git a/src/NSubstitute/Core/SequenceChecking/SequenceFormatter.cs b/src/NSubstitute/Core/SequenceChecking/SequenceFormatter.cs index e407a334..71ff35ac 100644 --- a/src/NSubstitute/Core/SequenceChecking/SequenceFormatter.cs +++ b/src/NSubstitute/Core/SequenceChecking/SequenceFormatter.cs @@ -127,15 +127,9 @@ private IEnumerable ToEnumerable(T value) } } - private class ArgAndParamInfo + private class ArgAndParamInfo(ParameterInfo paramInfo, object? argument) { - public ParameterInfo ParamInfo { get; } - public object? Argument { get; } - - public ArgAndParamInfo(ParameterInfo paramInfo, object? argument) - { - ParamInfo = paramInfo; - Argument = argument; - } + public ParameterInfo ParamInfo { get; } = paramInfo; + public object? Argument { get; } = argument; } } \ No newline at end of file diff --git a/src/NSubstitute/Core/SubstituteFactory.cs b/src/NSubstitute/Core/SubstituteFactory.cs index 27b96e6e..76a9f652 100644 --- a/src/NSubstitute/Core/SubstituteFactory.cs +++ b/src/NSubstitute/Core/SubstituteFactory.cs @@ -3,18 +3,8 @@ namespace NSubstitute.Core; -public class SubstituteFactory : ISubstituteFactory +public class SubstituteFactory(ISubstituteStateFactory substituteStateFactory, ICallRouterFactory callRouterFactory, IProxyFactory proxyFactory) : ISubstituteFactory { - private readonly ISubstituteStateFactory _substituteStateFactory; - private readonly ICallRouterFactory _callRouterFactory; - private readonly IProxyFactory _proxyFactory; - - public SubstituteFactory(ISubstituteStateFactory substituteStateFactory, ICallRouterFactory callRouterFactory, IProxyFactory proxyFactory) - { - _substituteStateFactory = substituteStateFactory; - _callRouterFactory = callRouterFactory; - _proxyFactory = proxyFactory; - } /// /// Create a substitute for the given types. @@ -48,15 +38,15 @@ public object CreatePartial(Type[] typesToProxy, object?[] constructorArguments) private object Create(Type[] typesToProxy, object?[] constructorArguments, bool callBaseByDefault) { - var substituteState = _substituteStateFactory.Create(this); + var substituteState = substituteStateFactory.Create(this); substituteState.CallBaseConfiguration.CallBaseByDefault = callBaseByDefault; var primaryProxyType = GetPrimaryProxyType(typesToProxy); var canConfigureBaseCalls = callBaseByDefault || CanCallBaseImplementation(primaryProxyType); - var callRouter = _callRouterFactory.Create(substituteState, canConfigureBaseCalls); + var callRouter = callRouterFactory.Create(substituteState, canConfigureBaseCalls); var additionalTypes = typesToProxy.Where(x => x != primaryProxyType).ToArray(); - var proxy = _proxyFactory.GenerateProxy(callRouter, primaryProxyType, additionalTypes, constructorArguments); + var proxy = proxyFactory.GenerateProxy(callRouter, primaryProxyType, additionalTypes, constructorArguments); return proxy; } diff --git a/src/NSubstitute/Core/SubstituteStateFactory.cs b/src/NSubstitute/Core/SubstituteStateFactory.cs index ade9f17c..5789a157 100644 --- a/src/NSubstitute/Core/SubstituteStateFactory.cs +++ b/src/NSubstitute/Core/SubstituteStateFactory.cs @@ -2,24 +2,13 @@ namespace NSubstitute.Core; -public class SubstituteStateFactory : ISubstituteStateFactory +public class SubstituteStateFactory(ICallSpecificationFactory callSpecificationFactory, + ICallInfoFactory callInfoFactory, + IAutoValueProvidersFactory autoValueProvidersFactory) : ISubstituteStateFactory { - private readonly ICallSpecificationFactory _callSpecificationFactory; - private readonly ICallInfoFactory _callInfoFactory; - private readonly IAutoValueProvidersFactory _autoValueProvidersFactory; - - public SubstituteStateFactory(ICallSpecificationFactory callSpecificationFactory, - ICallInfoFactory callInfoFactory, - IAutoValueProvidersFactory autoValueProvidersFactory) - { - _callSpecificationFactory = callSpecificationFactory; - _callInfoFactory = callInfoFactory; - _autoValueProvidersFactory = autoValueProvidersFactory; - } - public ISubstituteState Create(ISubstituteFactory substituteFactory) { - var autoValueProviders = _autoValueProvidersFactory.CreateProviders(substituteFactory); - return new SubstituteState(_callSpecificationFactory, _callInfoFactory, autoValueProviders); + var autoValueProviders = autoValueProvidersFactory.CreateProviders(substituteFactory); + return new SubstituteState(callSpecificationFactory, callInfoFactory, autoValueProviders); } } \ No newline at end of file diff --git a/src/NSubstitute/Core/ThreadLocalContext.cs b/src/NSubstitute/Core/ThreadLocalContext.cs index 3fbbb4a4..73e1100b 100644 --- a/src/NSubstitute/Core/ThreadLocalContext.cs +++ b/src/NSubstitute/Core/ThreadLocalContext.cs @@ -148,40 +148,33 @@ public void RegisterInContextQuery(ICall call) query.RegisterCall(call); } - private class PendingSpecificationWrapper : IPendingSpecification + private class PendingSpecificationWrapper(RobustThreadLocal valueHolder) : IPendingSpecification { - private readonly RobustThreadLocal _valueHolder; - - public PendingSpecificationWrapper(RobustThreadLocal valueHolder) - { - _valueHolder = valueHolder; - } - public bool HasPendingCallSpecInfo() { - return _valueHolder.Value.HasValue; + return valueHolder.Value.HasValue; } public PendingSpecificationInfo? UseCallSpecInfo() { - var info = _valueHolder.Value; + var info = valueHolder.Value; Clear(); return info.ToPendingSpecificationInfo(); } public void SetCallSpecification(ICallSpecification callSpecification) { - _valueHolder.Value = PendingSpecInfoData.FromCallSpecification(callSpecification); + valueHolder.Value = PendingSpecInfoData.FromCallSpecification(callSpecification); } public void SetLastCall(ICall lastCall) { - _valueHolder.Value = PendingSpecInfoData.FromLastCall(lastCall); + valueHolder.Value = PendingSpecInfoData.FromLastCall(lastCall); } public void Clear() { - _valueHolder.Value = default; + valueHolder.Value = default; } } diff --git a/src/NSubstitute/Core/WhenCalled.cs b/src/NSubstitute/Core/WhenCalled.cs index c15b9691..6ba33312 100644 --- a/src/NSubstitute/Core/WhenCalled.cs +++ b/src/NSubstitute/Core/WhenCalled.cs @@ -5,24 +5,11 @@ namespace NSubstitute.Core; -public class WhenCalled +public class WhenCalled(ISubstitutionContext context, T substitute, Action call, MatchArgs matchArgs) { - private readonly T _substitute; - private readonly Action _call; - private readonly MatchArgs _matchArgs; - private readonly ICallRouter _callRouter; - private readonly IThreadLocalContext _threadContext; - private readonly IRouteFactory _routeFactory; - - public WhenCalled(ISubstitutionContext context, T substitute, Action call, MatchArgs matchArgs) - { - _substitute = substitute; - _call = call; - _matchArgs = matchArgs; - _callRouter = context.GetCallRouterFor(substitute!); - _routeFactory = context.RouteFactory; - _threadContext = context.ThreadContext; - } + private readonly ICallRouter _callRouter = context.GetCallRouterFor(substitute!); + private readonly IThreadLocalContext _threadContext = context.ThreadContext; + private readonly IRouteFactory _routeFactory = context.RouteFactory; /// /// Perform this action when called. @@ -30,8 +17,8 @@ public WhenCalled(ISubstitutionContext context, T substitute, Action call, Ma /// public void Do(Action callbackWithArguments) { - _threadContext.SetNextRoute(_callRouter, x => _routeFactory.DoWhenCalled(x, callbackWithArguments, _matchArgs)); - _call(_substitute); + _threadContext.SetNextRoute(_callRouter, x => _routeFactory.DoWhenCalled(x, callbackWithArguments, matchArgs)); + call(substitute); } /// @@ -40,8 +27,8 @@ public void Do(Action callbackWithArguments) /// public void Do(Callback callback) { - _threadContext.SetNextRoute(_callRouter, x => _routeFactory.DoWhenCalled(x, callback.Call, _matchArgs)); - _call(_substitute); + _threadContext.SetNextRoute(_callRouter, x => _routeFactory.DoWhenCalled(x, callback.Call, matchArgs)); + call(substitute); } /// @@ -49,8 +36,8 @@ public void Do(Callback callback) /// public void DoNotCallBase() { - _threadContext.SetNextRoute(_callRouter, x => _routeFactory.DoNotCallBase(x, _matchArgs)); - _call(_substitute); + _threadContext.SetNextRoute(_callRouter, x => _routeFactory.DoNotCallBase(x, matchArgs)); + call(substitute); } /// @@ -58,8 +45,8 @@ public void DoNotCallBase() /// public void CallBase() { - _threadContext.SetNextRoute(_callRouter, x => _routeFactory.CallBase(x, _matchArgs)); - _call(_substitute); + _threadContext.SetNextRoute(_callRouter, x => _routeFactory.CallBase(x, matchArgs)); + call(substitute); } /// diff --git a/src/NSubstitute/Exceptions/ArgumentIsNotOutOrRefException.cs b/src/NSubstitute/Exceptions/ArgumentIsNotOutOrRefException.cs index 3d33144a..1f5e605c 100644 --- a/src/NSubstitute/Exceptions/ArgumentIsNotOutOrRefException.cs +++ b/src/NSubstitute/Exceptions/ArgumentIsNotOutOrRefException.cs @@ -1,11 +1,6 @@ namespace NSubstitute.Exceptions; -public class ArgumentIsNotOutOrRefException : SubstituteException +public class ArgumentIsNotOutOrRefException(int argumentIndex, Type argumentType) : SubstituteException(string.Format(WhatProbablyWentWrong, argumentIndex, argumentType.Name)) { private const string WhatProbablyWentWrong = "Could not set argument {0} ({1}) as it is not an out or ref argument."; - - public ArgumentIsNotOutOrRefException(int argumentIndex, Type argumentType) - : base(string.Format(WhatProbablyWentWrong, argumentIndex, argumentType.Name)) - { - } } diff --git a/src/NSubstitute/Exceptions/ArgumentNotFoundException.cs b/src/NSubstitute/Exceptions/ArgumentNotFoundException.cs index c34c9a52..0a75f6ba 100644 --- a/src/NSubstitute/Exceptions/ArgumentNotFoundException.cs +++ b/src/NSubstitute/Exceptions/ArgumentNotFoundException.cs @@ -1,6 +1,5 @@ namespace NSubstitute.Exceptions; -public class ArgumentNotFoundException : SubstituteException +public class ArgumentNotFoundException(string message) : SubstituteException(message) { - public ArgumentNotFoundException(string message) : base(message) { } } diff --git a/src/NSubstitute/Exceptions/ArgumentSetWithIncompatibleValueException.cs b/src/NSubstitute/Exceptions/ArgumentSetWithIncompatibleValueException.cs index 505ee753..cfb0bfdd 100644 --- a/src/NSubstitute/Exceptions/ArgumentSetWithIncompatibleValueException.cs +++ b/src/NSubstitute/Exceptions/ArgumentSetWithIncompatibleValueException.cs @@ -1,10 +1,7 @@ namespace NSubstitute.Exceptions; -public class ArgumentSetWithIncompatibleValueException : SubstituteException +public class ArgumentSetWithIncompatibleValueException(int argumentIndex, Type argumentType, Type typeOfValueWeTriedToAssign) : SubstituteException(string.Format(WhatProbablyWentWrong, argumentIndex, argumentType.Name, typeOfValueWeTriedToAssign.Name)) { private const string WhatProbablyWentWrong = "Could not set value of type {2} to argument {0} ({1}) because the types are incompatible."; - - public ArgumentSetWithIncompatibleValueException(int argumentIndex, Type argumentType, Type typeOfValueWeTriedToAssign) - : base(string.Format(WhatProbablyWentWrong, argumentIndex, argumentType.Name, typeOfValueWeTriedToAssign.Name)) { } } diff --git a/src/NSubstitute/Exceptions/CallSequenceNotFoundException.cs b/src/NSubstitute/Exceptions/CallSequenceNotFoundException.cs index 30e478d5..101992e4 100644 --- a/src/NSubstitute/Exceptions/CallSequenceNotFoundException.cs +++ b/src/NSubstitute/Exceptions/CallSequenceNotFoundException.cs @@ -1,6 +1,5 @@ namespace NSubstitute.Exceptions; -public class CallSequenceNotFoundException : SubstituteException +public class CallSequenceNotFoundException(string message) : SubstituteException(message) { - public CallSequenceNotFoundException(string message) : base(message) { } } diff --git a/src/NSubstitute/Exceptions/CanNotPartiallySubForInterfaceOrDelegateException.cs b/src/NSubstitute/Exceptions/CanNotPartiallySubForInterfaceOrDelegateException.cs index 112e325b..58040298 100644 --- a/src/NSubstitute/Exceptions/CanNotPartiallySubForInterfaceOrDelegateException.cs +++ b/src/NSubstitute/Exceptions/CanNotPartiallySubForInterfaceOrDelegateException.cs @@ -1,8 +1,7 @@ namespace NSubstitute.Exceptions; -public class CanNotPartiallySubForInterfaceOrDelegateException : SubstituteException +public class CanNotPartiallySubForInterfaceOrDelegateException(Type type) : SubstituteException(DescribeProblem(type)) { - public CanNotPartiallySubForInterfaceOrDelegateException(Type type) : base(DescribeProblem(type)) { } private static string DescribeProblem(Type type) { return string.Format("Can only substitute for parts of classes, not interfaces or delegates. " diff --git a/src/NSubstitute/Exceptions/CannotReturnNullforValueType.cs b/src/NSubstitute/Exceptions/CannotReturnNullforValueType.cs index ddfffdb7..9f304937 100644 --- a/src/NSubstitute/Exceptions/CannotReturnNullforValueType.cs +++ b/src/NSubstitute/Exceptions/CannotReturnNullforValueType.cs @@ -1,10 +1,8 @@ namespace NSubstitute.Exceptions; -public class CannotReturnNullForValueType : SubstituteException +public class CannotReturnNullForValueType(Type valueType) : SubstituteException(string.Format(Description, valueType.Name)) { private const string Description = "Cannot return null for {0} because it is a value type. " + "If you want to return the default value for this type use \"default({0})\"."; - - public CannotReturnNullForValueType(Type valueType) : base(string.Format(Description, valueType.Name)) { } } diff --git a/src/NSubstitute/Exceptions/CouldNotConfigureBaseMethodException.cs b/src/NSubstitute/Exceptions/CouldNotConfigureBaseMethodException.cs index 839e005d..8ea388b9 100644 --- a/src/NSubstitute/Exceptions/CouldNotConfigureBaseMethodException.cs +++ b/src/NSubstitute/Exceptions/CouldNotConfigureBaseMethodException.cs @@ -1,6 +1,6 @@ namespace NSubstitute.Exceptions; -public class CouldNotConfigureCallBaseException : SubstituteException +public class CouldNotConfigureCallBaseException(string message) : SubstituteException(message) { private const string CannotConfigureSingleCallMessage = "Cannot configure the base method call as base method implementation is missing. " + @@ -15,8 +15,4 @@ internal static CouldNotConfigureCallBaseException ForSingleCall() => internal static CouldNotConfigureCallBaseException ForAllCalls() => new CouldNotConfigureCallBaseException(CannotConfigureAllCallsMessage); - - public CouldNotConfigureCallBaseException(string message) : base(message) - { - } } \ No newline at end of file diff --git a/src/NSubstitute/Exceptions/CouldNotSetReturnException.cs b/src/NSubstitute/Exceptions/CouldNotSetReturnException.cs index f050b23c..151c1a58 100644 --- a/src/NSubstitute/Exceptions/CouldNotSetReturnException.cs +++ b/src/NSubstitute/Exceptions/CouldNotSetReturnException.cs @@ -2,7 +2,7 @@ namespace NSubstitute.Exceptions; -public abstract class CouldNotSetReturnException : SubstituteException +public abstract class CouldNotSetReturnException(string s) : SubstituteException(s + "\n\n" + WhatProbablyWentWrong) { protected const string WhatProbablyWentWrong = "Make sure you called Returns() after calling your substitute (for example: mySub.SomeMethod().Returns(value)),\n" + @@ -20,8 +20,6 @@ public abstract class CouldNotSetReturnException : SubstituteException "\tvar returnValue = ConfigOtherSub();\n" + "\tmySub.SomeMethod().Returns(returnValue);\n" + ""; - - protected CouldNotSetReturnException(string s) : base(s + "\n\n" + WhatProbablyWentWrong) { } } public class CouldNotSetReturnDueToNoLastCallException : CouldNotSetReturnException @@ -37,10 +35,8 @@ public class CouldNotSetReturnDueToMissingInfoAboutLastCallException : CouldNotS } -public class CouldNotSetReturnDueToTypeMismatchException : CouldNotSetReturnException +public class CouldNotSetReturnDueToTypeMismatchException(Type? returnType, MethodInfo member) : CouldNotSetReturnException(DescribeProblem(returnType, member)) { - public CouldNotSetReturnDueToTypeMismatchException(Type? returnType, MethodInfo member) : base(DescribeProblem(returnType, member)) { } - private static string DescribeProblem(Type? typeOfReturnValue, MethodInfo member) { return typeOfReturnValue == null diff --git a/src/NSubstitute/Exceptions/RedundantArgumentMatcherException.cs b/src/NSubstitute/Exceptions/RedundantArgumentMatcherException.cs index a7029062..0ee3fdd7 100644 --- a/src/NSubstitute/Exceptions/RedundantArgumentMatcherException.cs +++ b/src/NSubstitute/Exceptions/RedundantArgumentMatcherException.cs @@ -3,7 +3,7 @@ namespace NSubstitute.Exceptions; -public class RedundantArgumentMatcherException : SubstituteException +public class RedundantArgumentMatcherException(string message) : SubstituteException(message) { public RedundantArgumentMatcherException(IEnumerable remainingSpecifications, IEnumerable allSpecifications) @@ -11,10 +11,6 @@ public RedundantArgumentMatcherException(IEnumerable rem { } - public RedundantArgumentMatcherException(string message) : base(message) - { - } - private static string FormatErrorMessage(IEnumerable remainingSpecifications, IEnumerable allSpecifications) { diff --git a/src/NSubstitute/Exceptions/SubstituteException.cs b/src/NSubstitute/Exceptions/SubstituteException.cs index 53ff063f..5184479c 100644 --- a/src/NSubstitute/Exceptions/SubstituteException.cs +++ b/src/NSubstitute/Exceptions/SubstituteException.cs @@ -1,8 +1,7 @@ namespace NSubstitute.Exceptions; -public class SubstituteException : Exception +public class SubstituteException(string message, Exception? innerException) : Exception(message, innerException) { public SubstituteException() : this("") { } public SubstituteException(string message) : this(message, null) { } - public SubstituteException(string message, Exception? innerException) : base(message, innerException) { } } diff --git a/src/NSubstitute/Exceptions/SubstituteInternalException.cs b/src/NSubstitute/Exceptions/SubstituteInternalException.cs index 6616725d..e96c4413 100644 --- a/src/NSubstitute/Exceptions/SubstituteInternalException.cs +++ b/src/NSubstitute/Exceptions/SubstituteInternalException.cs @@ -1,12 +1,9 @@ namespace NSubstitute.Exceptions; -public class SubstituteInternalException : SubstituteException +public class SubstituteInternalException(string message, Exception? innerException) : SubstituteException("Please report this exception at https://github.com/nsubstitute/NSubstitute/issues: \n\n" + message, + innerException) { public SubstituteInternalException() : this("") { } public SubstituteInternalException(string message) : this(message, null) { } - public SubstituteInternalException(string message, Exception? innerException) - : base("Please report this exception at https://github.com/nsubstitute/NSubstitute/issues: \n\n" + message, - innerException) - { } } \ No newline at end of file diff --git a/src/NSubstitute/Exceptions/UnexpectedArgumentMatcherException.cs b/src/NSubstitute/Exceptions/UnexpectedArgumentMatcherException.cs index 8b4200d1..1e251c69 100644 --- a/src/NSubstitute/Exceptions/UnexpectedArgumentMatcherException.cs +++ b/src/NSubstitute/Exceptions/UnexpectedArgumentMatcherException.cs @@ -1,6 +1,6 @@ namespace NSubstitute.Exceptions; -public class UnexpectedArgumentMatcherException : SubstituteException +public class UnexpectedArgumentMatcherException(string message) : SubstituteException(message) { public static readonly string WhatProbablyWentWrong = "Argument matchers (Arg.Is, Arg.Any) should only be used in place of member arguments. " + @@ -10,5 +10,4 @@ public class UnexpectedArgumentMatcherException : SubstituteException "Incorrect use:" + Environment.NewLine + " sub.MyMethod(\"hi\").Returns(Arg.Any())"; public UnexpectedArgumentMatcherException() : this(WhatProbablyWentWrong) { } - public UnexpectedArgumentMatcherException(string message) : base(message) { } } diff --git a/src/NSubstitute/Extensions/ReceivedExtensions.cs b/src/NSubstitute/Extensions/ReceivedExtensions.cs index a79ce0f8..e3413c6f 100644 --- a/src/NSubstitute/Extensions/ReceivedExtensions.cs +++ b/src/NSubstitute/Extensions/ReceivedExtensions.cs @@ -87,10 +87,10 @@ public abstract class Quantity /// A string describing the required quantity of items identified by the provided noun forms. public abstract string Describe(string singularNoun, string pluralNoun); - private class ExactQuantity : Quantity + private class ExactQuantity(int number) : Quantity { - private readonly int _number; - public ExactQuantity(int number) { _number = number; } + private readonly int _number = number; + public override bool Matches(IEnumerable items) { return _number == items.Count(); } public override bool RequiresMoreThan(IEnumerable items) { return _number > items.Count(); } public override string Describe(string singularNoun, string pluralNoun) diff --git a/src/NSubstitute/Proxies/CastleDynamicProxy/CastleDynamicProxyFactory.cs b/src/NSubstitute/Proxies/CastleDynamicProxy/CastleDynamicProxyFactory.cs index 97d20354..e1c0d1ef 100644 --- a/src/NSubstitute/Proxies/CastleDynamicProxy/CastleDynamicProxyFactory.cs +++ b/src/NSubstitute/Proxies/CastleDynamicProxy/CastleDynamicProxyFactory.cs @@ -5,20 +5,10 @@ namespace NSubstitute.Proxies.CastleDynamicProxy; -public class CastleDynamicProxyFactory : IProxyFactory +public class CastleDynamicProxyFactory(ICallFactory callFactory, IArgumentSpecificationDequeue argSpecificationDequeue) : IProxyFactory { - private readonly ICallFactory _callFactory; - private readonly IArgumentSpecificationDequeue _argSpecificationDequeue; - private readonly ProxyGenerator _proxyGenerator; - private readonly AllMethodsExceptCallRouterCallsHook _allMethodsExceptCallRouterCallsHook; - - public CastleDynamicProxyFactory(ICallFactory callFactory, IArgumentSpecificationDequeue argSpecificationDequeue) - { - _callFactory = callFactory; - _argSpecificationDequeue = argSpecificationDequeue; - _proxyGenerator = new ProxyGenerator(); - _allMethodsExceptCallRouterCallsHook = new AllMethodsExceptCallRouterCallsHook(); - } + private readonly ProxyGenerator _proxyGenerator = new ProxyGenerator(); + private readonly AllMethodsExceptCallRouterCallsHook _allMethodsExceptCallRouterCallsHook = new AllMethodsExceptCallRouterCallsHook(); public object GenerateProxy(ICallRouter callRouter, Type typeToProxy, Type[]? additionalInterfaces, object?[]? constructorArguments) { @@ -77,8 +67,8 @@ private CastleForwardingInterceptor CreateForwardingInterceptor(ICallRouter call { return new CastleForwardingInterceptor( new CastleInvocationMapper( - _callFactory, - _argSpecificationDequeue), + callFactory, + argSpecificationDequeue), callRouter); } @@ -184,15 +174,8 @@ private static bool IsNotBaseObjectMethod(MethodInfo methodInfo) => methodInfo.GetBaseDefinition().DeclaringType != typeof(object); } - private class StaticCallRouterProvider : ICallRouterProvider + private class StaticCallRouterProvider(ICallRouter callRouter) : ICallRouterProvider { - private readonly ICallRouter _callRouter; - - public StaticCallRouterProvider(ICallRouter callRouter) - { - _callRouter = callRouter; - } - - public ICallRouter GetCallRouter() => _callRouter; + public ICallRouter GetCallRouter() => callRouter; } } \ No newline at end of file diff --git a/src/NSubstitute/Proxies/CastleDynamicProxy/CastleForwardingInterceptor.cs b/src/NSubstitute/Proxies/CastleDynamicProxy/CastleForwardingInterceptor.cs index d818da07..d2e8949b 100644 --- a/src/NSubstitute/Proxies/CastleDynamicProxy/CastleForwardingInterceptor.cs +++ b/src/NSubstitute/Proxies/CastleDynamicProxy/CastleForwardingInterceptor.cs @@ -3,31 +3,23 @@ namespace NSubstitute.Proxies.CastleDynamicProxy; -public class CastleForwardingInterceptor : IInterceptor +public class CastleForwardingInterceptor(CastleInvocationMapper invocationMapper, ICallRouter callRouter) : IInterceptor { - private readonly CastleInvocationMapper _invocationMapper; - private readonly ICallRouter _callRouter; private bool _fullDispatchMode; - public CastleForwardingInterceptor(CastleInvocationMapper invocationMapper, ICallRouter callRouter) - { - _invocationMapper = invocationMapper; - _callRouter = callRouter; - } - public void Intercept(IInvocation invocation) { - ICall mappedInvocation = _invocationMapper.Map(invocation); + ICall mappedInvocation = invocationMapper.Map(invocation); if (_fullDispatchMode) { - invocation.ReturnValue = _callRouter.Route(mappedInvocation); + invocation.ReturnValue = callRouter.Route(mappedInvocation); return; } // Fallback to the base value until the full dispatch mode is activated. // Useful to ensure that object is initialized properly. - if (_callRouter.CallBaseByDefault) + if (callRouter.CallBaseByDefault) { invocation.ReturnValue = mappedInvocation.TryCallBase().ValueOrDefault(); } diff --git a/src/NSubstitute/Proxies/CastleDynamicProxy/CastleInvocationMapper.cs b/src/NSubstitute/Proxies/CastleDynamicProxy/CastleInvocationMapper.cs index 8b48a50f..7ebac3e9 100644 --- a/src/NSubstitute/Proxies/CastleDynamicProxy/CastleInvocationMapper.cs +++ b/src/NSubstitute/Proxies/CastleDynamicProxy/CastleInvocationMapper.cs @@ -3,17 +3,8 @@ namespace NSubstitute.Proxies.CastleDynamicProxy; -public class CastleInvocationMapper +public class CastleInvocationMapper(ICallFactory callFactory, IArgumentSpecificationDequeue argSpecificationDequeue) { - private readonly ICallFactory _callFactory; - private readonly IArgumentSpecificationDequeue _argSpecificationDequeue; - - public CastleInvocationMapper(ICallFactory callFactory, IArgumentSpecificationDequeue argSpecificationDequeue) - { - _callFactory = callFactory; - _argSpecificationDequeue = argSpecificationDequeue; - } - public virtual ICall Map(IInvocation castleInvocation) { Func? baseMethod = null; @@ -25,8 +16,8 @@ public virtual ICall Map(IInvocation castleInvocation) baseMethod = CreateBaseResultInvocation(castleInvocation); } - var queuedArgSpecifications = _argSpecificationDequeue.DequeueAllArgumentSpecificationsForMethod(castleInvocation.Arguments.Length); - return _callFactory.Create(castleInvocation.Method, castleInvocation.Arguments, castleInvocation.Proxy, queuedArgSpecifications, baseMethod); + var queuedArgSpecifications = argSpecificationDequeue.DequeueAllArgumentSpecificationsForMethod(castleInvocation.Arguments.Length); + return callFactory.Create(castleInvocation.Method, castleInvocation.Arguments, castleInvocation.Proxy, queuedArgSpecifications, baseMethod); } private static Func CreateBaseResultInvocation(IInvocation invocation) diff --git a/src/NSubstitute/Proxies/CastleDynamicProxy/ProxyIdInterceptor.cs b/src/NSubstitute/Proxies/CastleDynamicProxy/ProxyIdInterceptor.cs index 19c244fc..7902fae4 100644 --- a/src/NSubstitute/Proxies/CastleDynamicProxy/ProxyIdInterceptor.cs +++ b/src/NSubstitute/Proxies/CastleDynamicProxy/ProxyIdInterceptor.cs @@ -5,16 +5,10 @@ namespace NSubstitute.Proxies.CastleDynamicProxy; -public class ProxyIdInterceptor : IInterceptor +public class ProxyIdInterceptor(Type primaryProxyType) : IInterceptor { - private readonly Type _primaryProxyType; private string? _cachedProxyId; - public ProxyIdInterceptor(Type primaryProxyType) - { - _primaryProxyType = primaryProxyType; - } - public void Intercept(IInvocation invocation) { if (IsDefaultToStringMethod(invocation.Method)) @@ -30,7 +24,7 @@ private string GenerateId(IInvocation invocation) { var proxy = invocation.InvocationTarget; - var shortTypeName = _primaryProxyType.GetNonMangledTypeName(); + var shortTypeName = primaryProxyType.GetNonMangledTypeName(); var proxyHashCode = proxy.GetHashCode(); return string.Format(CultureInfo.InvariantCulture, "Substitute.{0}|{1:x8}", shortTypeName, proxyHashCode); diff --git a/src/NSubstitute/Proxies/DelegateProxy/DelegateProxyFactory.cs b/src/NSubstitute/Proxies/DelegateProxy/DelegateProxyFactory.cs index 6b81f51d..9e38a1c1 100644 --- a/src/NSubstitute/Proxies/DelegateProxy/DelegateProxyFactory.cs +++ b/src/NSubstitute/Proxies/DelegateProxy/DelegateProxyFactory.cs @@ -4,14 +4,9 @@ namespace NSubstitute.Proxies.DelegateProxy; [Obsolete("This class is deprecated and will be removed in future versions of the product.")] -public class DelegateProxyFactory : IProxyFactory +public class DelegateProxyFactory(CastleDynamicProxyFactory objectProxyFactory) : IProxyFactory { - private readonly CastleDynamicProxyFactory _castleObjectProxyFactory; - - public DelegateProxyFactory(CastleDynamicProxyFactory objectProxyFactory) - { - _castleObjectProxyFactory = objectProxyFactory ?? throw new ArgumentNullException(nameof(objectProxyFactory)); - } + private readonly CastleDynamicProxyFactory _castleObjectProxyFactory = objectProxyFactory ?? throw new ArgumentNullException(nameof(objectProxyFactory)); public object GenerateProxy(ICallRouter callRouter, Type typeToProxy, Type[]? additionalInterfaces, object?[]? constructorArguments) { diff --git a/src/NSubstitute/Proxies/DelegateProxy/ProxiedDelegateTypeAttribute.cs b/src/NSubstitute/Proxies/DelegateProxy/ProxiedDelegateTypeAttribute.cs index 26f5cb10..7ea54948 100644 --- a/src/NSubstitute/Proxies/DelegateProxy/ProxiedDelegateTypeAttribute.cs +++ b/src/NSubstitute/Proxies/DelegateProxy/ProxiedDelegateTypeAttribute.cs @@ -2,12 +2,7 @@ namespace NSubstitute.Proxies.DelegateProxy; [Obsolete("This class is deprecated and will be removed in future versions of the product.")] [AttributeUsage(AttributeTargets.Method)] -public class ProxiedDelegateTypeAttribute : Attribute +public class ProxiedDelegateTypeAttribute(Type delegateType) : Attribute { - public Type DelegateType { get; } - - public ProxiedDelegateTypeAttribute(Type delegateType) - { - DelegateType = delegateType; - } + public Type DelegateType { get; } = delegateType; } \ No newline at end of file diff --git a/src/NSubstitute/Proxies/ProxyFactory.cs b/src/NSubstitute/Proxies/ProxyFactory.cs index 3833fce5..f107ae85 100644 --- a/src/NSubstitute/Proxies/ProxyFactory.cs +++ b/src/NSubstitute/Proxies/ProxyFactory.cs @@ -3,22 +3,13 @@ namespace NSubstitute.Proxies; [Obsolete("This class is deprecated and will be removed in future versions of the product.")] -public class ProxyFactory : IProxyFactory +public class ProxyFactory(IProxyFactory delegateFactory, IProxyFactory dynamicProxyFactory) : IProxyFactory { - private readonly IProxyFactory _delegateFactory; - private readonly IProxyFactory _dynamicProxyFactory; - - public ProxyFactory(IProxyFactory delegateFactory, IProxyFactory dynamicProxyFactory) - { - _delegateFactory = delegateFactory; - _dynamicProxyFactory = dynamicProxyFactory; - } - public object GenerateProxy(ICallRouter callRouter, Type typeToProxy, Type[]? additionalInterfaces, object?[]? constructorArguments) { var isDelegate = typeToProxy.IsDelegate(); return isDelegate - ? _delegateFactory.GenerateProxy(callRouter, typeToProxy, additionalInterfaces, constructorArguments) - : _dynamicProxyFactory.GenerateProxy(callRouter, typeToProxy, additionalInterfaces, constructorArguments); + ? delegateFactory.GenerateProxy(callRouter, typeToProxy, additionalInterfaces, constructorArguments) + : dynamicProxyFactory.GenerateProxy(callRouter, typeToProxy, additionalInterfaces, constructorArguments); } } \ No newline at end of file diff --git a/src/NSubstitute/Routing/AutoValues/AutoObservableProvider.cs b/src/NSubstitute/Routing/AutoValues/AutoObservableProvider.cs index 177ff40f..713a5bde 100644 --- a/src/NSubstitute/Routing/AutoValues/AutoObservableProvider.cs +++ b/src/NSubstitute/Routing/AutoValues/AutoObservableProvider.cs @@ -3,15 +3,8 @@ namespace NSubstitute.Routing.AutoValues; -public class AutoObservableProvider : IAutoValueProvider +public class AutoObservableProvider(Lazy> autoValueProviders) : IAutoValueProvider { - private readonly Lazy> _autoValueProviders; - - public AutoObservableProvider(Lazy> autoValueProviders) - { - _autoValueProviders = autoValueProviders; - } - public bool CanProvideValueFor(Type type) => type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(IObservable<>); @@ -21,7 +14,7 @@ public bool CanProvideValueFor(Type type) => throw new InvalidOperationException(); Type innerType = type.GetGenericArguments()[0]; - var valueProvider = _autoValueProviders.Value.FirstOrDefault(vp => vp.CanProvideValueFor(innerType)); + var valueProvider = autoValueProviders.Value.FirstOrDefault(vp => vp.CanProvideValueFor(innerType)); var value = valueProvider == null ? GetDefault(type) : valueProvider.GetValue(innerType); return Activator.CreateInstance(typeof(ReturnObservable<>).MakeGenericType(innerType), [value]); } diff --git a/src/NSubstitute/Routing/AutoValues/AutoSubstituteProvider.cs b/src/NSubstitute/Routing/AutoValues/AutoSubstituteProvider.cs index eaa8ac0a..e9dd7599 100644 --- a/src/NSubstitute/Routing/AutoValues/AutoSubstituteProvider.cs +++ b/src/NSubstitute/Routing/AutoValues/AutoSubstituteProvider.cs @@ -3,15 +3,8 @@ namespace NSubstitute.Routing.AutoValues; -public class AutoSubstituteProvider : IAutoValueProvider +public class AutoSubstituteProvider(ISubstituteFactory substituteFactory) : IAutoValueProvider { - private readonly ISubstituteFactory _substituteFactory; - - public AutoSubstituteProvider(ISubstituteFactory substituteFactory) - { - _substituteFactory = substituteFactory; - } - public bool CanProvideValueFor(Type type) { return type.GetTypeInfo().IsInterface @@ -21,7 +14,7 @@ public bool CanProvideValueFor(Type type) public object GetValue(Type type) { - return _substituteFactory.Create([type], []); + return substituteFactory.Create([type], []); } private bool IsPureVirtualClassWithParameterlessConstructor(Type type) diff --git a/src/NSubstitute/Routing/AutoValues/AutoTaskProvider.cs b/src/NSubstitute/Routing/AutoValues/AutoTaskProvider.cs index e106df3e..13d365f3 100644 --- a/src/NSubstitute/Routing/AutoValues/AutoTaskProvider.cs +++ b/src/NSubstitute/Routing/AutoValues/AutoTaskProvider.cs @@ -2,15 +2,8 @@ namespace NSubstitute.Routing.AutoValues; -public class AutoTaskProvider : IAutoValueProvider +public class AutoTaskProvider(Lazy> autoValueProviders) : IAutoValueProvider { - private readonly Lazy> _autoValueProviders; - - public AutoTaskProvider(Lazy> autoValueProviders) - { - _autoValueProviders = autoValueProviders; - } - public bool CanProvideValueFor(Type type) => typeof(Task).IsAssignableFrom(type); public object GetValue(Type type) @@ -21,7 +14,7 @@ public object GetValue(Type type) if (type.GetTypeInfo().IsGenericType) { var taskType = type.GetGenericArguments()[0]; - var valueProvider = _autoValueProviders.Value.FirstOrDefault(vp => vp.CanProvideValueFor(taskType)); + var valueProvider = autoValueProviders.Value.FirstOrDefault(vp => vp.CanProvideValueFor(taskType)); var value = valueProvider == null ? GetDefault(type) : valueProvider.GetValue(taskType); var taskCompletionSourceType = typeof(TaskCompletionSource<>).MakeGenericType(taskType); diff --git a/src/NSubstitute/Routing/Handlers/AddCallToQueryResultHandler.cs b/src/NSubstitute/Routing/Handlers/AddCallToQueryResultHandler.cs index 5b276285..e3000a03 100644 --- a/src/NSubstitute/Routing/Handlers/AddCallToQueryResultHandler.cs +++ b/src/NSubstitute/Routing/Handlers/AddCallToQueryResultHandler.cs @@ -2,18 +2,11 @@ namespace NSubstitute.Routing.Handlers; -public class AddCallToQueryResultHandler : ICallHandler +public class AddCallToQueryResultHandler(IThreadLocalContext threadContext) : ICallHandler { - private readonly IThreadLocalContext _threadContext; - - public AddCallToQueryResultHandler(IThreadLocalContext threadContext) - { - _threadContext = threadContext; - } - public RouteAction Handle(ICall call) { - _threadContext.RegisterInContextQuery(call); + threadContext.RegisterInContextQuery(call); return RouteAction.Continue(); } diff --git a/src/NSubstitute/Routing/Handlers/CallBaseForCallHandler.cs b/src/NSubstitute/Routing/Handlers/CallBaseForCallHandler.cs index 749a54cc..0748e980 100644 --- a/src/NSubstitute/Routing/Handlers/CallBaseForCallHandler.cs +++ b/src/NSubstitute/Routing/Handlers/CallBaseForCallHandler.cs @@ -3,25 +3,14 @@ namespace NSubstitute.Routing.Handlers; -public class CallBaseForCallHandler : ICallHandler +public class CallBaseForCallHandler(ICallSpecificationFactory callSpecificationFactory, ICallBaseConfiguration callBaseConfig, MatchArgs matchArgs) : ICallHandler { - private readonly ICallSpecificationFactory _callSpecificationFactory; - private readonly ICallBaseConfiguration _callBaseConfig; - private readonly MatchArgs _matchArgs; - - public CallBaseForCallHandler(ICallSpecificationFactory callSpecificationFactory, ICallBaseConfiguration callBaseConfig, MatchArgs matchArgs) - { - _callSpecificationFactory = callSpecificationFactory; - _callBaseConfig = callBaseConfig; - _matchArgs = matchArgs; - } - public RouteAction Handle(ICall call) { if (!call.CanCallBase) throw CouldNotConfigureCallBaseException.ForSingleCall(); - var callSpec = _callSpecificationFactory.CreateFrom(call, _matchArgs); - _callBaseConfig.Include(callSpec); + var callSpec = callSpecificationFactory.CreateFrom(call, matchArgs); + callBaseConfig.Include(callSpec); return RouteAction.Continue(); } diff --git a/src/NSubstitute/Routing/Handlers/CheckReceivedCallsHandler.cs b/src/NSubstitute/Routing/Handlers/CheckReceivedCallsHandler.cs index de7c5816..e16fd389 100644 --- a/src/NSubstitute/Routing/Handlers/CheckReceivedCallsHandler.cs +++ b/src/NSubstitute/Routing/Handlers/CheckReceivedCallsHandler.cs @@ -3,35 +3,20 @@ namespace NSubstitute.Routing.Handlers; -public class CheckReceivedCallsHandler : ICallHandler +public class CheckReceivedCallsHandler(ICallCollection receivedCalls, ICallSpecificationFactory callSpecificationFactory, IReceivedCallsExceptionThrower exceptionThrower, MatchArgs matchArgs, Quantity requiredQuantity) : ICallHandler { - private readonly ICallCollection _receivedCalls; - private readonly ICallSpecificationFactory _callSpecificationFactory; - private readonly IReceivedCallsExceptionThrower _exceptionThrower; - private readonly MatchArgs _matchArgs; - private readonly Quantity _requiredQuantity; - - public CheckReceivedCallsHandler(ICallCollection receivedCalls, ICallSpecificationFactory callSpecificationFactory, IReceivedCallsExceptionThrower exceptionThrower, MatchArgs matchArgs, Quantity requiredQuantity) - { - _receivedCalls = receivedCalls; - _callSpecificationFactory = callSpecificationFactory; - _exceptionThrower = exceptionThrower; - _matchArgs = matchArgs; - _requiredQuantity = requiredQuantity; - } - public RouteAction Handle(ICall call) { - var callSpecification = _callSpecificationFactory.CreateFrom(call, _matchArgs); - var allCallsToMethodSpec = _callSpecificationFactory.CreateFrom(call, MatchArgs.Any); + var callSpecification = callSpecificationFactory.CreateFrom(call, matchArgs); + var allCallsToMethodSpec = callSpecificationFactory.CreateFrom(call, MatchArgs.Any); - var allCalls = _receivedCalls.AllCalls().ToList(); + var allCalls = receivedCalls.AllCalls().ToList(); var matchingCalls = allCalls.Where(callSpecification.IsSatisfiedBy).ToList(); - if (!_requiredQuantity.Matches(matchingCalls)) + if (!requiredQuantity.Matches(matchingCalls)) { var relatedCalls = allCalls.Where(allCallsToMethodSpec.IsSatisfiedBy).Except(matchingCalls); - _exceptionThrower.Throw(callSpecification, matchingCalls, relatedCalls, _requiredQuantity); + exceptionThrower.Throw(callSpecification, matchingCalls, relatedCalls, requiredQuantity); } return RouteAction.Continue(); diff --git a/src/NSubstitute/Routing/Handlers/ClearLastCallRouterHandler.cs b/src/NSubstitute/Routing/Handlers/ClearLastCallRouterHandler.cs index 793ff625..2e112d0e 100644 --- a/src/NSubstitute/Routing/Handlers/ClearLastCallRouterHandler.cs +++ b/src/NSubstitute/Routing/Handlers/ClearLastCallRouterHandler.cs @@ -8,18 +8,11 @@ namespace NSubstitute.Routing.Handlers; /// /// This is to help prevent static state bleeding over into future calls. /// -public class ClearLastCallRouterHandler : ICallHandler +public class ClearLastCallRouterHandler(IThreadLocalContext threadContext) : ICallHandler { - private readonly IThreadLocalContext _threadContext; - - public ClearLastCallRouterHandler(IThreadLocalContext threadContext) - { - _threadContext = threadContext; - } - public RouteAction Handle(ICall call) { - _threadContext.ClearLastCallRouter(); + threadContext.ClearLastCallRouter(); return RouteAction.Continue(); } diff --git a/src/NSubstitute/Routing/Handlers/ClearUnusedCallSpecHandler.cs b/src/NSubstitute/Routing/Handlers/ClearUnusedCallSpecHandler.cs index 9154a960..8818617f 100644 --- a/src/NSubstitute/Routing/Handlers/ClearUnusedCallSpecHandler.cs +++ b/src/NSubstitute/Routing/Handlers/ClearUnusedCallSpecHandler.cs @@ -2,18 +2,11 @@ namespace NSubstitute.Routing.Handlers; -public class ClearUnusedCallSpecHandler : ICallHandler +public class ClearUnusedCallSpecHandler(IPendingSpecification pendingSpecification) : ICallHandler { - private readonly IPendingSpecification _pendingSpecification; - - public ClearUnusedCallSpecHandler(IPendingSpecification pendingSpecification) - { - _pendingSpecification = pendingSpecification; - } - public RouteAction Handle(ICall call) { - _pendingSpecification.Clear(); + pendingSpecification.Clear(); return RouteAction.Continue(); } diff --git a/src/NSubstitute/Routing/Handlers/DoActionsCallHandler.cs b/src/NSubstitute/Routing/Handlers/DoActionsCallHandler.cs index bd3fa4fd..859e4551 100644 --- a/src/NSubstitute/Routing/Handlers/DoActionsCallHandler.cs +++ b/src/NSubstitute/Routing/Handlers/DoActionsCallHandler.cs @@ -2,18 +2,11 @@ namespace NSubstitute.Routing.Handlers; -public class DoActionsCallHandler : ICallHandler +public class DoActionsCallHandler(ICallActions callActions) : ICallHandler { - private readonly ICallActions _callActions; - - public DoActionsCallHandler(ICallActions callActions) - { - _callActions = callActions; - } - public RouteAction Handle(ICall call) { - _callActions.InvokeMatchingActions(call); + callActions.InvokeMatchingActions(call); return RouteAction.Continue(); } diff --git a/src/NSubstitute/Routing/Handlers/DoNotCallBaseForCallHandler.cs b/src/NSubstitute/Routing/Handlers/DoNotCallBaseForCallHandler.cs index 78fce881..6e1e223b 100644 --- a/src/NSubstitute/Routing/Handlers/DoNotCallBaseForCallHandler.cs +++ b/src/NSubstitute/Routing/Handlers/DoNotCallBaseForCallHandler.cs @@ -3,25 +3,14 @@ namespace NSubstitute.Routing.Handlers; -public class DoNotCallBaseForCallHandler : ICallHandler +public class DoNotCallBaseForCallHandler(ICallSpecificationFactory callSpecificationFactory, ICallBaseConfiguration callBaseConfig, MatchArgs matchArgs) : ICallHandler { - private readonly ICallSpecificationFactory _callSpecificationFactory; - private readonly ICallBaseConfiguration _callBaseConfig; - private readonly MatchArgs _matchArgs; - - public DoNotCallBaseForCallHandler(ICallSpecificationFactory callSpecificationFactory, ICallBaseConfiguration callBaseConfig, MatchArgs matchArgs) - { - _callSpecificationFactory = callSpecificationFactory; - _callBaseConfig = callBaseConfig; - _matchArgs = matchArgs; - } - public RouteAction Handle(ICall call) { if (!call.CanCallBase) throw CouldNotConfigureCallBaseException.ForSingleCall(); - var callSpec = _callSpecificationFactory.CreateFrom(call, _matchArgs); - _callBaseConfig.Exclude(callSpec); + var callSpec = callSpecificationFactory.CreateFrom(call, matchArgs); + callBaseConfig.Exclude(callSpec); return RouteAction.Continue(); } diff --git a/src/NSubstitute/Routing/Handlers/EventSubscriptionHandler.cs b/src/NSubstitute/Routing/Handlers/EventSubscriptionHandler.cs index 5ce3bdc2..cc394b00 100644 --- a/src/NSubstitute/Routing/Handlers/EventSubscriptionHandler.cs +++ b/src/NSubstitute/Routing/Handlers/EventSubscriptionHandler.cs @@ -3,21 +3,14 @@ namespace NSubstitute.Routing.Handlers; -public class EventSubscriptionHandler : ICallHandler +public class EventSubscriptionHandler(IEventHandlerRegistry eventHandlerRegistry) : ICallHandler { - private readonly IEventHandlerRegistry _eventHandlerRegistry; - - public EventSubscriptionHandler(IEventHandlerRegistry eventHandlerRegistry) - { - _eventHandlerRegistry = eventHandlerRegistry; - } - public RouteAction Handle(ICall call) { if (CanBeSubscribeUnsubscribeCall(call)) { - If(call, IsEventSubscription, _eventHandlerRegistry.Add); - If(call, IsEventUnsubscription, _eventHandlerRegistry.Remove); + If(call, IsEventSubscription, eventHandlerRegistry.Add); + If(call, IsEventUnsubscription, eventHandlerRegistry.Remove); } return RouteAction.Continue(); diff --git a/src/NSubstitute/Routing/Handlers/PropertySetterHandler.cs b/src/NSubstitute/Routing/Handlers/PropertySetterHandler.cs index 7319d748..9245fc62 100644 --- a/src/NSubstitute/Routing/Handlers/PropertySetterHandler.cs +++ b/src/NSubstitute/Routing/Handlers/PropertySetterHandler.cs @@ -2,27 +2,18 @@ namespace NSubstitute.Routing.Handlers; -public class PropertySetterHandler : ICallHandler +public class PropertySetterHandler(IPropertyHelper propertyHelper, IConfigureCall configureCall) : ICallHandler { - private readonly IPropertyHelper _propertyHelper; - private readonly IConfigureCall _configureCall; - - public PropertySetterHandler(IPropertyHelper propertyHelper, IConfigureCall configureCall) - { - _propertyHelper = propertyHelper; - _configureCall = configureCall; - } - public RouteAction Handle(ICall call) { - if (_propertyHelper.IsCallToSetAReadWriteProperty(call)) + if (propertyHelper.IsCallToSetAReadWriteProperty(call)) { - var callToPropertyGetter = _propertyHelper.CreateCallToPropertyGetterFromSetterCall(call); + var callToPropertyGetter = propertyHelper.CreateCallToPropertyGetterFromSetterCall(call); // It's important to use original arguments, as it provides better performance. // It's safe to use original arguments here, as only by-ref arguments might be modified, // which should never happen for this case. var valueBeingSetOnProperty = call.GetOriginalArguments().Last(); - _configureCall.SetResultForCall(callToPropertyGetter, new ReturnValue(valueBeingSetOnProperty), MatchArgs.AsSpecifiedInCall); + configureCall.SetResultForCall(callToPropertyGetter, new ReturnValue(valueBeingSetOnProperty), MatchArgs.AsSpecifiedInCall); } return RouteAction.Continue(); diff --git a/src/NSubstitute/Routing/Handlers/RaiseEventHandler.cs b/src/NSubstitute/Routing/Handlers/RaiseEventHandler.cs index bf668083..95bea67b 100644 --- a/src/NSubstitute/Routing/Handlers/RaiseEventHandler.cs +++ b/src/NSubstitute/Routing/Handlers/RaiseEventHandler.cs @@ -4,17 +4,8 @@ namespace NSubstitute.Routing.Handlers; -public class RaiseEventHandler : ICallHandler +public class RaiseEventHandler(IEventHandlerRegistry eventHandlerRegistry, Func getEventArguments) : ICallHandler { - private readonly IEventHandlerRegistry _eventHandlerRegistry; - private readonly Func _getEventArguments; - - public RaiseEventHandler(IEventHandlerRegistry eventHandlerRegistry, Func getEventArguments) - { - _eventHandlerRegistry = eventHandlerRegistry; - _getEventArguments = getEventArguments; - } - public RouteAction Handle(ICall call) { var methodInfo = call.GetMethodInfo(); @@ -24,8 +15,8 @@ public RouteAction Handle(ICall call) throw new CouldNotRaiseEventException(); } - object?[] eventArguments = _getEventArguments(call); - var handlers = _eventHandlerRegistry.GetHandlers(eventInfo.Name); + object?[] eventArguments = getEventArguments(call); + var handlers = eventHandlerRegistry.GetHandlers(eventInfo.Name); foreach (Delegate handler in handlers) { if (handler == null) diff --git a/src/NSubstitute/Routing/Handlers/RecordCallHandler.cs b/src/NSubstitute/Routing/Handlers/RecordCallHandler.cs index 828d641a..764815a1 100644 --- a/src/NSubstitute/Routing/Handlers/RecordCallHandler.cs +++ b/src/NSubstitute/Routing/Handlers/RecordCallHandler.cs @@ -2,21 +2,12 @@ namespace NSubstitute.Routing.Handlers; -public class RecordCallHandler : ICallHandler +public class RecordCallHandler(ICallCollection callCollection, SequenceNumberGenerator generator) : ICallHandler { - private readonly ICallCollection _callCollection; - private readonly SequenceNumberGenerator _generator; - - public RecordCallHandler(ICallCollection callCollection, SequenceNumberGenerator generator) - { - _callCollection = callCollection; - _generator = generator; - } - public RouteAction Handle(ICall call) { - call.AssignSequenceNumber(_generator.Next()); - _callCollection.Add(call); + call.AssignSequenceNumber(generator.Next()); + callCollection.Add(call); return RouteAction.Continue(); } diff --git a/src/NSubstitute/Routing/Handlers/RecordCallSpecificationHandler.cs b/src/NSubstitute/Routing/Handlers/RecordCallSpecificationHandler.cs index 654ba5ca..6e9f574d 100644 --- a/src/NSubstitute/Routing/Handlers/RecordCallSpecificationHandler.cs +++ b/src/NSubstitute/Routing/Handlers/RecordCallSpecificationHandler.cs @@ -2,29 +2,18 @@ namespace NSubstitute.Routing.Handlers; -public class RecordCallSpecificationHandler : ICallHandler +public class RecordCallSpecificationHandler(IPendingSpecification pendingCallSpecification, ICallSpecificationFactory callSpecificationFactory, ICallActions callActions) : ICallHandler { - private readonly IPendingSpecification _pendingCallSpecification; - private readonly ICallSpecificationFactory _callSpecificationFactory; - private readonly ICallActions _callActions; - - public RecordCallSpecificationHandler(IPendingSpecification pendingCallSpecification, ICallSpecificationFactory callSpecificationFactory, ICallActions callActions) - { - _pendingCallSpecification = pendingCallSpecification; - _callSpecificationFactory = callSpecificationFactory; - _callActions = callActions; - } - public RouteAction Handle(ICall call) { - var callSpec = _callSpecificationFactory.CreateFrom(call, MatchArgs.AsSpecifiedInCall); - _pendingCallSpecification.SetCallSpecification(callSpec); + var callSpec = callSpecificationFactory.CreateFrom(call, MatchArgs.AsSpecifiedInCall); + pendingCallSpecification.SetCallSpecification(callSpec); // Performance optimization - don't register call actions if current argument matchers // don't have any callbacks. if (call.GetArgumentSpecifications().Any(x => x.HasAction)) { - _callActions.Add(callSpec); + callActions.Add(callSpec); } return RouteAction.Continue(); diff --git a/src/NSubstitute/Routing/Handlers/ReturnAutoValue.cs b/src/NSubstitute/Routing/Handlers/ReturnAutoValue.cs index 0c325766..6116cb3c 100644 --- a/src/NSubstitute/Routing/Handlers/ReturnAutoValue.cs +++ b/src/NSubstitute/Routing/Handlers/ReturnAutoValue.cs @@ -8,24 +8,13 @@ public enum AutoValueBehaviour UseValueForSubsequentCalls, ReturnAndForgetValue } -public class ReturnAutoValue : ICallHandler +public class ReturnAutoValue(AutoValueBehaviour autoValueBehaviour, IEnumerable autoValueProviders, ICallResults callResults, ICallSpecificationFactory callSpecificationFactory) : ICallHandler { - private readonly IAutoValueProvider[] _autoValueProviders; - private readonly ICallResults _callResults; - private readonly ICallSpecificationFactory _callSpecificationFactory; - private readonly AutoValueBehaviour _autoValueBehaviour; - - public ReturnAutoValue(AutoValueBehaviour autoValueBehaviour, IEnumerable autoValueProviders, ICallResults callResults, ICallSpecificationFactory callSpecificationFactory) - { - _autoValueProviders = autoValueProviders.AsArray(); - _callResults = callResults; - _callSpecificationFactory = callSpecificationFactory; - _autoValueBehaviour = autoValueBehaviour; - } + private readonly IAutoValueProvider[] _autoValueProviders = autoValueProviders.AsArray(); public RouteAction Handle(ICall call) { - if (_callResults.TryGetResult(call, out var cachedResult)) + if (callResults.TryGetResult(call, out var cachedResult)) { return RouteAction.Return(cachedResult); } @@ -48,10 +37,10 @@ public RouteAction Handle(ICall call) private object? GetResultValueUsingProvider(ICall call, Type type, IAutoValueProvider provider) { var valueToReturn = provider.GetValue(type); - if (_autoValueBehaviour == AutoValueBehaviour.UseValueForSubsequentCalls) + if (autoValueBehaviour == AutoValueBehaviour.UseValueForSubsequentCalls) { - var spec = _callSpecificationFactory.CreateFrom(call, MatchArgs.AsSpecifiedInCall); - _callResults.SetResult(spec, new ReturnValue(valueToReturn)); + var spec = callSpecificationFactory.CreateFrom(call, MatchArgs.AsSpecifiedInCall); + callResults.SetResult(spec, new ReturnValue(valueToReturn)); } return valueToReturn; diff --git a/src/NSubstitute/Routing/Handlers/ReturnConfiguredResultHandler.cs b/src/NSubstitute/Routing/Handlers/ReturnConfiguredResultHandler.cs index 244e5713..e50c7785 100644 --- a/src/NSubstitute/Routing/Handlers/ReturnConfiguredResultHandler.cs +++ b/src/NSubstitute/Routing/Handlers/ReturnConfiguredResultHandler.cs @@ -2,18 +2,11 @@ namespace NSubstitute.Routing.Handlers; -public class ReturnConfiguredResultHandler : ICallHandler +public class ReturnConfiguredResultHandler(ICallResults callResults) : ICallHandler { - private readonly ICallResults _callResults; - - public ReturnConfiguredResultHandler(ICallResults callResults) - { - _callResults = callResults; - } - public RouteAction Handle(ICall call) { - if (_callResults.TryGetResult(call, out var configuredResult)) + if (callResults.TryGetResult(call, out var configuredResult)) { return RouteAction.Return(configuredResult); } diff --git a/src/NSubstitute/Routing/Handlers/ReturnDefaultForReturnTypeHandler.cs b/src/NSubstitute/Routing/Handlers/ReturnDefaultForReturnTypeHandler.cs index ff0b9170..32c08c4a 100644 --- a/src/NSubstitute/Routing/Handlers/ReturnDefaultForReturnTypeHandler.cs +++ b/src/NSubstitute/Routing/Handlers/ReturnDefaultForReturnTypeHandler.cs @@ -2,18 +2,11 @@ namespace NSubstitute.Routing.Handlers; -public class ReturnDefaultForReturnTypeHandler : ICallHandler +public class ReturnDefaultForReturnTypeHandler(IDefaultForType defaultForType) : ICallHandler { - private readonly IDefaultForType _defaultForType; - - public ReturnDefaultForReturnTypeHandler(IDefaultForType defaultForType) - { - _defaultForType = defaultForType; - } - public RouteAction Handle(ICall call) { - var returnValue = _defaultForType.GetDefaultFor(call.GetMethodInfo().ReturnType); + var returnValue = defaultForType.GetDefaultFor(call.GetMethodInfo().ReturnType); return RouteAction.Return(returnValue); } } \ No newline at end of file diff --git a/src/NSubstitute/Routing/Handlers/ReturnFromAndConfigureDynamicCall.cs b/src/NSubstitute/Routing/Handlers/ReturnFromAndConfigureDynamicCall.cs index 976e1b28..235eab2f 100644 --- a/src/NSubstitute/Routing/Handlers/ReturnFromAndConfigureDynamicCall.cs +++ b/src/NSubstitute/Routing/Handlers/ReturnFromAndConfigureDynamicCall.cs @@ -3,22 +3,16 @@ namespace NSubstitute.Routing.Handlers; -public class ReturnFromAndConfigureDynamicCall : ICallHandler +public class ReturnFromAndConfigureDynamicCall(IConfigureCall configureCall) : ICallHandler { private static readonly Type DynamicAttributeType = typeof(DynamicAttribute); - private readonly IConfigureCall _configureCall; - - public ReturnFromAndConfigureDynamicCall(IConfigureCall configureCall) - { - _configureCall = configureCall; - } public RouteAction Handle(ICall call) { if (ReturnsDynamic(call)) { var stubToReturn = new DynamicStub(); - _configureCall.SetResultForCall(call, new ReturnValue(stubToReturn), MatchArgs.AsSpecifiedInCall); + configureCall.SetResultForCall(call, new ReturnValue(stubToReturn), MatchArgs.AsSpecifiedInCall); return RouteAction.Return(new DynamicStub()); } else diff --git a/src/NSubstitute/Routing/Handlers/ReturnFromBaseIfRequired.cs b/src/NSubstitute/Routing/Handlers/ReturnFromBaseIfRequired.cs index 457bce15..9daf119b 100644 --- a/src/NSubstitute/Routing/Handlers/ReturnFromBaseIfRequired.cs +++ b/src/NSubstitute/Routing/Handlers/ReturnFromBaseIfRequired.cs @@ -2,18 +2,11 @@ namespace NSubstitute.Routing.Handlers; -public class ReturnFromBaseIfRequired : ICallHandler +public class ReturnFromBaseIfRequired(ICallBaseConfiguration config) : ICallHandler { - private readonly ICallBaseConfiguration _config; - - public ReturnFromBaseIfRequired(ICallBaseConfiguration config) - { - _config = config; - } - public RouteAction Handle(ICall call) { - if (_config.ShouldCallBase(call)) + if (config.ShouldCallBase(call)) { return call .TryCallBase() diff --git a/src/NSubstitute/Routing/Handlers/ReturnFromCustomHandlers.cs b/src/NSubstitute/Routing/Handlers/ReturnFromCustomHandlers.cs index 85d93594..16202ade 100644 --- a/src/NSubstitute/Routing/Handlers/ReturnFromCustomHandlers.cs +++ b/src/NSubstitute/Routing/Handlers/ReturnFromCustomHandlers.cs @@ -2,24 +2,17 @@ namespace NSubstitute.Routing.Handlers; -public class ReturnFromCustomHandlers : ICallHandler +public class ReturnFromCustomHandlers(ICustomHandlers customHandlers) : ICallHandler { - private readonly ICustomHandlers _customHandlers; - - public ReturnFromCustomHandlers(ICustomHandlers customHandlers) - { - _customHandlers = customHandlers; - } - public RouteAction Handle(ICall call) { // Performance optimization, as enumerator retrieval allocates. - if (_customHandlers.Handlers.Count == 0) + if (customHandlers.Handlers.Count == 0) { return RouteAction.Continue(); } - foreach (var handler in _customHandlers.Handlers) + foreach (var handler in customHandlers.Handlers) { var result = handler.Handle(call); if (result.HasReturnValue) diff --git a/src/NSubstitute/Routing/Handlers/ReturnResultForTypeHandler.cs b/src/NSubstitute/Routing/Handlers/ReturnResultForTypeHandler.cs index ab445ce8..e627af0a 100644 --- a/src/NSubstitute/Routing/Handlers/ReturnResultForTypeHandler.cs +++ b/src/NSubstitute/Routing/Handlers/ReturnResultForTypeHandler.cs @@ -2,18 +2,11 @@ namespace NSubstitute.Routing.Handlers; -public class ReturnResultForTypeHandler : ICallHandler +public class ReturnResultForTypeHandler(IResultsForType resultsForType) : ICallHandler { - private readonly IResultsForType _resultsForType; - - public ReturnResultForTypeHandler(IResultsForType resultsForType) - { - _resultsForType = resultsForType; - } - public RouteAction Handle(ICall call) { - if (_resultsForType.TryGetResult(call, out var result)) + if (resultsForType.TryGetResult(call, out var result)) { return RouteAction.Return(result); } diff --git a/src/NSubstitute/Routing/Handlers/SetActionForCallHandler.cs b/src/NSubstitute/Routing/Handlers/SetActionForCallHandler.cs index 89cdb945..aa0db72d 100644 --- a/src/NSubstitute/Routing/Handlers/SetActionForCallHandler.cs +++ b/src/NSubstitute/Routing/Handlers/SetActionForCallHandler.cs @@ -2,25 +2,16 @@ namespace NSubstitute.Routing.Handlers; -public class SetActionForCallHandler : ICallHandler +public class SetActionForCallHandler( + ICallSpecificationFactory callSpecificationFactory, + ICallActions callActions, + Action action, + MatchArgs matchArgs) : ICallHandler { - private readonly ICallSpecificationFactory _callSpecificationFactory; - private readonly ICallActions _callActions; - private readonly Action _action; - private readonly MatchArgs _matchArgs; - - public SetActionForCallHandler(ICallSpecificationFactory callSpecificationFactory, ICallActions callActions, Action action, MatchArgs matchArgs) - { - _callSpecificationFactory = callSpecificationFactory; - _callActions = callActions; - _action = action; - _matchArgs = matchArgs; - } - public RouteAction Handle(ICall call) { - var callSpec = _callSpecificationFactory.CreateFrom(call, _matchArgs); - _callActions.Add(callSpec, _action); + var callSpec = callSpecificationFactory.CreateFrom(call, matchArgs); + callActions.Add(callSpec, action); return RouteAction.Continue(); } diff --git a/src/NSubstitute/Routing/Handlers/TrackLastCallHandler.cs b/src/NSubstitute/Routing/Handlers/TrackLastCallHandler.cs index 3afa6358..225db13f 100644 --- a/src/NSubstitute/Routing/Handlers/TrackLastCallHandler.cs +++ b/src/NSubstitute/Routing/Handlers/TrackLastCallHandler.cs @@ -2,18 +2,11 @@ namespace NSubstitute.Routing.Handlers; -public class TrackLastCallHandler : ICallHandler +public class TrackLastCallHandler(IPendingSpecification pendingSpecification) : ICallHandler { - private readonly IPendingSpecification _pendingSpecification; - - public TrackLastCallHandler(IPendingSpecification pendingSpecification) - { - _pendingSpecification = pendingSpecification; - } - public RouteAction Handle(ICall call) { - _pendingSpecification.SetLastCall(call); + pendingSpecification.SetLastCall(call); return RouteAction.Continue(); } diff --git a/src/NSubstitute/Routing/Route.cs b/src/NSubstitute/Routing/Route.cs index 4e3e8bff..ba84cc0a 100644 --- a/src/NSubstitute/Routing/Route.cs +++ b/src/NSubstitute/Routing/Route.cs @@ -2,24 +2,17 @@ namespace NSubstitute.Routing; -public class Route : IRoute +public class Route(ICallHandler[] handlers) : IRoute { - private readonly ICallHandler[] _handlers; - - public Route(ICallHandler[] handlers) - { - _handlers = handlers; - } - - public IEnumerable Handlers => _handlers; + public IEnumerable Handlers => handlers; public object? Handle(ICall call) { // This is a hot method which is invoked frequently and has major impact on performance. // Therefore, the LINQ cycle was unwinded to for loop. - for (int i = 0; i < _handlers.Length; i++) + for (int i = 0; i < handlers.Length; i++) { - var result = _handlers[i].Handle(call); + var result = handlers[i].Handle(call); if (result.HasReturnValue) { return result.ReturnValue; diff --git a/src/NSubstitute/Routing/RouteFactory.cs b/src/NSubstitute/Routing/RouteFactory.cs index 4808bb62..a89e3d5e 100644 --- a/src/NSubstitute/Routing/RouteFactory.cs +++ b/src/NSubstitute/Routing/RouteFactory.cs @@ -4,81 +4,64 @@ namespace NSubstitute.Routing; -public class RouteFactory : IRouteFactory +public class RouteFactory(SequenceNumberGenerator sequenceNumberGenerator, + IThreadLocalContext threadLocalContext, + ICallSpecificationFactory callSpecificationFactory, + IReceivedCallsExceptionThrower receivedCallsExceptionThrower, + IPropertyHelper propertyHelper, + IDefaultForType defaultForType) : IRouteFactory { - private readonly SequenceNumberGenerator _sequenceNumberGenerator; - private readonly IThreadLocalContext _threadLocalContext; - private readonly ICallSpecificationFactory _callSpecificationFactory; - private readonly IReceivedCallsExceptionThrower _receivedCallsExceptionThrower; - private readonly IPropertyHelper _propertyHelper; - private readonly IDefaultForType _defaultForType; - - public RouteFactory(SequenceNumberGenerator sequenceNumberGenerator, - IThreadLocalContext threadLocalContext, - ICallSpecificationFactory callSpecificationFactory, - IReceivedCallsExceptionThrower receivedCallsExceptionThrower, - IPropertyHelper propertyHelper, - IDefaultForType defaultForType) - { - _sequenceNumberGenerator = sequenceNumberGenerator; - _threadLocalContext = threadLocalContext; - _callSpecificationFactory = callSpecificationFactory; - _receivedCallsExceptionThrower = receivedCallsExceptionThrower; - _propertyHelper = propertyHelper; - _defaultForType = defaultForType; - } - public IRoute CallQuery(ISubstituteState state) { return new Route([ - new ClearUnusedCallSpecHandler(_threadLocalContext.PendingSpecification), - new AddCallToQueryResultHandler(_threadLocalContext), - new ReturnAutoValue(AutoValueBehaviour.UseValueForSubsequentCalls, state.AutoValueProviders, state.AutoValuesCallResults, _callSpecificationFactory), + new ClearUnusedCallSpecHandler(threadLocalContext.PendingSpecification), + new AddCallToQueryResultHandler(threadLocalContext), + new ReturnAutoValue(AutoValueBehaviour.UseValueForSubsequentCalls, state.AutoValueProviders, state.AutoValuesCallResults, callSpecificationFactory), ReturnDefaultForReturnTypeHandler() ]); } public IRoute CheckReceivedCalls(ISubstituteState state, MatchArgs matchArgs, Quantity requiredQuantity) { return new Route([ - new ClearLastCallRouterHandler(_threadLocalContext), - new ClearUnusedCallSpecHandler(_threadLocalContext.PendingSpecification), - new CheckReceivedCallsHandler(state.ReceivedCalls, _callSpecificationFactory, _receivedCallsExceptionThrower, matchArgs, requiredQuantity), - new ReturnAutoValue(AutoValueBehaviour.ReturnAndForgetValue, state.AutoValueProviders, state.AutoValuesCallResults, _callSpecificationFactory), + new ClearLastCallRouterHandler(threadLocalContext), + new ClearUnusedCallSpecHandler(threadLocalContext.PendingSpecification), + new CheckReceivedCallsHandler(state.ReceivedCalls, callSpecificationFactory, receivedCallsExceptionThrower, matchArgs, requiredQuantity), + new ReturnAutoValue(AutoValueBehaviour.ReturnAndForgetValue, state.AutoValueProviders, state.AutoValuesCallResults, callSpecificationFactory), ReturnDefaultForReturnTypeHandler() ]); } public IRoute DoWhenCalled(ISubstituteState state, Action doAction, MatchArgs matchArgs) { return new Route([ - new ClearLastCallRouterHandler(_threadLocalContext), - new ClearUnusedCallSpecHandler(_threadLocalContext.PendingSpecification), - new SetActionForCallHandler(_callSpecificationFactory, state.CallActions, doAction, matchArgs), + new ClearLastCallRouterHandler(threadLocalContext), + new ClearUnusedCallSpecHandler(threadLocalContext.PendingSpecification), + new SetActionForCallHandler(callSpecificationFactory, state.CallActions, doAction, matchArgs), ReturnDefaultForReturnTypeHandler() ]); } public IRoute DoNotCallBase(ISubstituteState state, MatchArgs matchArgs) { return new Route([ - new ClearLastCallRouterHandler(_threadLocalContext), - new ClearUnusedCallSpecHandler(_threadLocalContext.PendingSpecification), - new DoNotCallBaseForCallHandler(_callSpecificationFactory, state.CallBaseConfiguration, matchArgs), + new ClearLastCallRouterHandler(threadLocalContext), + new ClearUnusedCallSpecHandler(threadLocalContext.PendingSpecification), + new DoNotCallBaseForCallHandler(callSpecificationFactory, state.CallBaseConfiguration, matchArgs), ReturnDefaultForReturnTypeHandler() ]); } public IRoute CallBase(ISubstituteState state, MatchArgs matchArgs) { return new Route([ - new ClearLastCallRouterHandler(_threadLocalContext), - new ClearUnusedCallSpecHandler(_threadLocalContext.PendingSpecification), - new CallBaseForCallHandler(_callSpecificationFactory, state.CallBaseConfiguration, matchArgs), + new ClearLastCallRouterHandler(threadLocalContext), + new ClearUnusedCallSpecHandler(threadLocalContext.PendingSpecification), + new CallBaseForCallHandler(callSpecificationFactory, state.CallBaseConfiguration, matchArgs), ReturnDefaultForReturnTypeHandler() ]); } public IRoute RaiseEvent(ISubstituteState state, Func getEventArguments) { return new Route([ - new ClearLastCallRouterHandler(_threadLocalContext), - new ClearUnusedCallSpecHandler(_threadLocalContext.PendingSpecification), + new ClearLastCallRouterHandler(threadLocalContext), + new ClearUnusedCallSpecHandler(threadLocalContext.PendingSpecification), new RaiseEventHandler(state.EventHandlerRegistry, getEventArguments), ReturnDefaultForReturnTypeHandler() ]); @@ -86,9 +69,9 @@ public IRoute RaiseEvent(ISubstituteState state, Func getEvent public IRoute RecordCallSpecification(ISubstituteState state) { return new Route([ - new RecordCallSpecificationHandler(_threadLocalContext.PendingSpecification, _callSpecificationFactory, state.CallActions), - new PropertySetterHandler(_propertyHelper, state.ConfigureCall), - new ReturnAutoValue(AutoValueBehaviour.UseValueForSubsequentCalls, state.AutoValueProviders, state.AutoValuesCallResults, _callSpecificationFactory), + new RecordCallSpecificationHandler(threadLocalContext.PendingSpecification, callSpecificationFactory, state.CallActions), + new PropertySetterHandler(propertyHelper, state.ConfigureCall), + new ReturnAutoValue(AutoValueBehaviour.UseValueForSubsequentCalls, state.AutoValueProviders, state.AutoValuesCallResults, callSpecificationFactory), new ReturnFromAndConfigureDynamicCall(state.ConfigureCall), ReturnDefaultForReturnTypeHandler() ]); @@ -96,20 +79,20 @@ public IRoute RecordCallSpecification(ISubstituteState state) public IRoute RecordReplay(ISubstituteState state) { return new Route([ - new TrackLastCallHandler(_threadLocalContext.PendingSpecification), - new RecordCallHandler(state.ReceivedCalls, _sequenceNumberGenerator), + new TrackLastCallHandler(threadLocalContext.PendingSpecification), + new RecordCallHandler(state.ReceivedCalls, sequenceNumberGenerator), new EventSubscriptionHandler(state.EventHandlerRegistry), - new PropertySetterHandler(_propertyHelper, state.ConfigureCall), + new PropertySetterHandler(propertyHelper, state.ConfigureCall), new DoActionsCallHandler(state.CallActions), new ReturnConfiguredResultHandler(state.CallResults), new ReturnResultForTypeHandler(state.ResultsForType), new ReturnFromBaseIfRequired(state.CallBaseConfiguration), new ReturnFromCustomHandlers(state.CustomHandlers), - new ReturnAutoValue(AutoValueBehaviour.UseValueForSubsequentCalls, state.AutoValueProviders, state.AutoValuesCallResults, _callSpecificationFactory), + new ReturnAutoValue(AutoValueBehaviour.UseValueForSubsequentCalls, state.AutoValueProviders, state.AutoValuesCallResults, callSpecificationFactory), new ReturnFromAndConfigureDynamicCall(state.ConfigureCall), ReturnDefaultForReturnTypeHandler() ]); } - private ReturnDefaultForReturnTypeHandler ReturnDefaultForReturnTypeHandler() => new(_defaultForType); + private ReturnDefaultForReturnTypeHandler ReturnDefaultForReturnTypeHandler() => new(defaultForType); } \ No newline at end of file diff --git a/tests/NSubstitute.Acceptance.Specs/ArgumentMatching.cs b/tests/NSubstitute.Acceptance.Specs/ArgumentMatching.cs index 517ed831..23151337 100644 --- a/tests/NSubstitute.Acceptance.Specs/ArgumentMatching.cs +++ b/tests/NSubstitute.Acceptance.Specs/ArgumentMatching.cs @@ -165,7 +165,7 @@ public void Received_for_async_method_can_be_awaited() TestReceivedAsync().Wait(); } - private async System.Threading.Tasks.Task TestReceivedAsync() + private async Task TestReceivedAsync() { await _something.Async(); await _something.Received().Async(); @@ -177,7 +177,7 @@ public void DidNotReceive_for_async_method_can_be_awaited() TestDidNotReceiveAsync().Wait(); } - private async System.Threading.Tasks.Task TestDidNotReceiveAsync() + private async Task TestDidNotReceiveAsync() { await _something.DidNotReceive().Async(); } diff --git a/tests/NSubstitute.Acceptance.Specs/ArgumentMatchingCompat.cs b/tests/NSubstitute.Acceptance.Specs/ArgumentMatchingCompat.cs index d6c43c2e..f22b905f 100644 --- a/tests/NSubstitute.Acceptance.Specs/ArgumentMatchingCompat.cs +++ b/tests/NSubstitute.Acceptance.Specs/ArgumentMatchingCompat.cs @@ -106,7 +106,7 @@ public void Received_for_async_method_can_be_awaited() TestReceivedAsync().Wait(); } - private async System.Threading.Tasks.Task TestReceivedAsync() + private async Task TestReceivedAsync() { await _something.Async(); await _something.Received().Async(); @@ -118,7 +118,7 @@ public void DidNotReceive_for_async_method_can_be_awaited() TestDidNotReceiveAsync().Wait(); } - private async System.Threading.Tasks.Task TestDidNotReceiveAsync() + private async Task TestDidNotReceiveAsync() { await _something.DidNotReceive().Async(); } diff --git a/tests/NSubstitute.Acceptance.Specs/AutoValuesForSubs.cs b/tests/NSubstitute.Acceptance.Specs/AutoValuesForSubs.cs index 0384bd8d..ea7cba97 100644 --- a/tests/NSubstitute.Acceptance.Specs/AutoValuesForSubs.cs +++ b/tests/NSubstitute.Acceptance.Specs/AutoValuesForSubs.cs @@ -177,9 +177,9 @@ public void Should_auto_return_a_completed_non_generic_task() public interface IFooWithTasks { - System.Threading.Tasks.Task GetSample(); - System.Threading.Tasks.Task GetIntAsync(); - System.Threading.Tasks.Task GetNonGenericTask(); + Task GetSample(); + Task GetIntAsync(); + Task GetNonGenericTask(); } [Test] @@ -224,18 +224,11 @@ public interface IFooWithObservable } //Copied from NSubstitute.Specs.AnonymousObserver (PR #137) - private class AnonymousObserver : IObserver - { - Action _onNext; - Action _onError; - Action _onCompleted; - - public AnonymousObserver(Action onNext, Action onError = null, Action onCompleted = null) - { - _onNext = onNext ?? (_ => { }); - _onError = onError ?? (_ => { }); - _onCompleted = onCompleted ?? (() => { }); - } + private class AnonymousObserver(Action onNext, Action onError = null, Action onCompleted = null) : IObserver + { + Action _onNext = onNext ?? (_ => { }); + Action _onError = onError ?? (_ => { }); + Action _onCompleted = onCompleted ?? (() => { }); public void OnNext(T value) { _onNext(value); } public void OnError(Exception error) { _onError(error); } diff --git a/tests/NSubstitute.Acceptance.Specs/CustomHandlersSpecs.cs b/tests/NSubstitute.Acceptance.Specs/CustomHandlersSpecs.cs index ab8eb35d..98a15bc7 100644 --- a/tests/NSubstitute.Acceptance.Specs/CustomHandlersSpecs.cs +++ b/tests/NSubstitute.Acceptance.Specs/CustomHandlersSpecs.cs @@ -219,15 +219,8 @@ public interface IValueSource string MethodWithArgs(string arg1, string arg2); } - private class ActionHandler : ICallHandler + private class ActionHandler(Func handler) : ICallHandler { - private readonly Func _handler; - - public ActionHandler(Func handler) - { - _handler = handler; - } - - public RouteAction Handle(ICall call) => _handler.Invoke(call); + public RouteAction Handle(ICall call) => handler.Invoke(call); } } \ No newline at end of file diff --git a/tests/NSubstitute.Acceptance.Specs/EventRaising.cs b/tests/NSubstitute.Acceptance.Specs/EventRaising.cs index ff467481..d0000c39 100644 --- a/tests/NSubstitute.Acceptance.Specs/EventRaising.cs +++ b/tests/NSubstitute.Acceptance.Specs/EventRaising.cs @@ -350,9 +350,8 @@ public interface IEventSamples public delegate int FuncDelegateWithArgs(int intArg, string stringArg); public delegate void CustomEventThatDoesNotInheritFromEventHandler(object sender, CustomEventArgs args); public class CustomEventArgs : EventArgs { } - public class CustomEventArgsWithNoDefaultCtor : EventArgs + public class CustomEventArgsWithNoDefaultCtor(string arg) : EventArgs { - public CustomEventArgsWithNoDefaultCtor(string arg) { } } public class CustomEventArgsWithInternalDefaultConstructor : EventArgs diff --git a/tests/NSubstitute.Acceptance.Specs/FieldReports/Issue378_InValueTypes.cs b/tests/NSubstitute.Acceptance.Specs/FieldReports/Issue378_InValueTypes.cs index 1f2527d9..39d8532e 100644 --- a/tests/NSubstitute.Acceptance.Specs/FieldReports/Issue378_InValueTypes.cs +++ b/tests/NSubstitute.Acceptance.Specs/FieldReports/Issue378_InValueTypes.cs @@ -7,14 +7,9 @@ namespace NSubstitute.Acceptance.Specs.FieldReports; /// public class Issue378_InValueTypes { - public readonly struct Struct + public readonly struct Struct(int value) { - public Struct(int value) - { - Value = value; - } - - public int Value { get; } + public int Value { get; } = value; } public interface IStructByReadOnlyRefConsumer { void Consume(in Struct value); } diff --git a/tests/NSubstitute.Acceptance.Specs/FieldReports/Issue500_SpecialMethodsWithoutAttribute.cs b/tests/NSubstitute.Acceptance.Specs/FieldReports/Issue500_SpecialMethodsWithoutAttribute.cs index 58e9cf68..089e5f71 100644 --- a/tests/NSubstitute.Acceptance.Specs/FieldReports/Issue500_SpecialMethodsWithoutAttribute.cs +++ b/tests/NSubstitute.Acceptance.Specs/FieldReports/Issue500_SpecialMethodsWithoutAttribute.cs @@ -88,25 +88,18 @@ private static Type GenerateTypeWithMissingSpecialNameAttributes() return typeBuilder.CreateTypeInfo().AsType(); } - private class GeneratedTypeFixture + private class GeneratedTypeFixture(object substitute) { - private readonly object _substitute; - - public GeneratedTypeFixture(object substitute) - { - _substitute = substitute; - } - public object MyProperty { - get => _substitute.GetType().GetProperty(PropertyName).GetValue(_substitute); - set => _substitute.GetType().GetProperty(PropertyName).SetValue(_substitute, value); + get => substitute.GetType().GetProperty(PropertyName).GetValue(substitute); + set => substitute.GetType().GetProperty(PropertyName).SetValue(substitute, value); } public event EventHandler MyEvent { - add => _substitute.GetType().GetEvent(EventName).AddEventHandler(_substitute, value); - remove => _substitute.GetType().GetEvent(EventName).RemoveEventHandler(_substitute, value); + add => substitute.GetType().GetEvent(EventName).AddEventHandler(substitute, value); + remove => substitute.GetType().GetEvent(EventName).RemoveEventHandler(substitute, value); } } } \ No newline at end of file diff --git a/tests/NSubstitute.Acceptance.Specs/FieldReports/Issue560_RaiseEventWithArrayArg.cs b/tests/NSubstitute.Acceptance.Specs/FieldReports/Issue560_RaiseEventWithArrayArg.cs index ebcaf1f0..ab16bf42 100644 --- a/tests/NSubstitute.Acceptance.Specs/FieldReports/Issue560_RaiseEventWithArrayArg.cs +++ b/tests/NSubstitute.Acceptance.Specs/FieldReports/Issue560_RaiseEventWithArrayArg.cs @@ -96,13 +96,8 @@ public interface IEventSamples event Action ActionWithParamsOfObjectArray; } - public class Widget + public class Widget(string name) { - public string Name { get; } - - public Widget(string name) - { - Name = name; - } + public string Name { get; } = name; } } \ No newline at end of file diff --git a/tests/NSubstitute.Acceptance.Specs/FieldReports/Issue75_DoesNotWorkWithMembersThatUseDynamic.cs b/tests/NSubstitute.Acceptance.Specs/FieldReports/Issue75_DoesNotWorkWithMembersThatUseDynamic.cs index 0383eaca..031aae3f 100644 --- a/tests/NSubstitute.Acceptance.Specs/FieldReports/Issue75_DoesNotWorkWithMembersThatUseDynamic.cs +++ b/tests/NSubstitute.Acceptance.Specs/FieldReports/Issue75_DoesNotWorkWithMembersThatUseDynamic.cs @@ -7,22 +7,13 @@ public class Issue75_DoesNotWorkWithMembersThatUseDynamic public interface ILog { void Error(Exception e); } public interface IClient { dynamic Post(string a, string b); } - public class ClassUnderTest + public class ClassUnderTest(IClient client, ILog log) { - private readonly IClient _client; - private readonly ILog _log; - - public ClassUnderTest(IClient client, ILog log) - { - _client = client; - _log = log; - } - public void Handle(string a) { - dynamic response = _client.Post("asdf", "fdsa"); + dynamic response = client.Post("asdf", "fdsa"); var error = response.error; - _log.Error(new Exception(error)); + log.Error(new Exception(error)); } } diff --git a/tests/NSubstitute.Acceptance.Specs/Infrastructure/ISomething.cs b/tests/NSubstitute.Acceptance.Specs/Infrastructure/ISomething.cs index 8d09264f..f4aa76f1 100644 --- a/tests/NSubstitute.Acceptance.Specs/Infrastructure/ISomething.cs +++ b/tests/NSubstitute.Acceptance.Specs/Infrastructure/ISomething.cs @@ -20,23 +20,23 @@ public interface ISomething int? NullableWithParams(int i, string s); object this[string key] { get; set; } - System.Threading.Tasks.Task Async(); - System.Threading.Tasks.Task DoAsync(object stuff); - System.Threading.Tasks.Task CountAsync(); - System.Threading.Tasks.Task AnythingAsync(object stuff); - System.Threading.Tasks.Task EchoAsync(int i); - System.Threading.Tasks.Task SayAsync(string s); - System.Threading.Tasks.Task SomeActionAsync(); - System.Threading.Tasks.Task SomeActionWithParamsAsync(int i, string s); - System.Threading.Tasks.Task NullableCountAsync(); - System.Threading.Tasks.Task NullableWithParamsAsync(int i, string s); + Task Async(); + Task DoAsync(object stuff); + Task CountAsync(); + Task AnythingAsync(object stuff); + Task EchoAsync(int i); + Task SayAsync(string s); + Task SomeActionAsync(); + Task SomeActionWithParamsAsync(int i, string s); + Task NullableCountAsync(); + Task NullableWithParamsAsync(int i, string s); - System.Threading.Tasks.ValueTask CountValueTaskAsync(); - System.Threading.Tasks.ValueTask EchoValueTaskAsync(int i); - System.Threading.Tasks.ValueTask AnythingValueTaskAsync(object stuff); - System.Threading.Tasks.ValueTask SayValueTaskAsync(string s); - System.Threading.Tasks.ValueTask SomeActionValueTaskAsync(); - System.Threading.Tasks.ValueTask SomeActionWithParamsValueTaskAsync(int i, string s); - System.Threading.Tasks.ValueTask NullableCountValueTaskAsync(); - System.Threading.Tasks.ValueTask NullableCountValueTaskWithParamsAsync(int i, string s); + ValueTask CountValueTaskAsync(); + ValueTask EchoValueTaskAsync(int i); + ValueTask AnythingValueTaskAsync(object stuff); + ValueTask SayValueTaskAsync(string s); + ValueTask SomeActionValueTaskAsync(); + ValueTask SomeActionWithParamsValueTaskAsync(int i, string s); + ValueTask NullableCountValueTaskAsync(); + ValueTask NullableCountValueTaskWithParamsAsync(int i, string s); } \ No newline at end of file diff --git a/tests/NSubstitute.Acceptance.Specs/MultipleThreads.cs b/tests/NSubstitute.Acceptance.Specs/MultipleThreads.cs index b1e26fd1..351a550f 100644 --- a/tests/NSubstitute.Acceptance.Specs/MultipleThreads.cs +++ b/tests/NSubstitute.Acceptance.Specs/MultipleThreads.cs @@ -118,7 +118,7 @@ public void Returns_multiple_values_is_threadsafe() sut.Number().Returns(expected[0], expected.Skip(1).ToArray()); var tasks = Enumerable.Range(0, parallelism) - .Select(_ => new System.Threading.Tasks.Task(() => sut.Number())) + .Select(_ => new Task(() => sut.Number())) .ToArray(); foreach (var task in tasks) { task.Start(); } diff --git a/tests/NSubstitute.Acceptance.Specs/NSubContainerTests.cs b/tests/NSubstitute.Acceptance.Specs/NSubContainerTests.cs index 1afb35e0..712f2521 100644 --- a/tests/NSubstitute.Acceptance.Specs/NSubContainerTests.cs +++ b/tests/NSubstitute.Acceptance.Specs/NSubContainerTests.cs @@ -63,7 +63,7 @@ public void ShouldAllowToResolveDependencyInFactoryMethod() var sut = new NSubContainer(); sut.Register(NSubLifetime.Transient); - sut.Register(r => new ClassWithDependency(r.Resolve()), NSubLifetime.Transient); + sut.Register(r => new ClassWithDependency(r.Resolve()), NSubLifetime.Transient); var result = sut.Resolve(); Assert.That(result, Is.Not.Null); @@ -151,7 +151,7 @@ public void ShouldReturnSameInstanceWhenResolvingDependencyInFactoryMethodForPer sut.Register(NSubLifetime.Transient); sut.Register(NSubLifetime.PerScope); - sut.Register( + sut.Register( r => new ClassWithMultipleDependencies(r.Resolve(), r.Resolve()), NSubLifetime.Transient); @@ -392,35 +392,19 @@ private TestImplNoPublicCtors() } } - public class ClassWithDependency + public class ClassWithDependency(ITestInterface dep) { - public ITestInterface Dep { get; } - - public ClassWithDependency(ITestInterface dep) - { - Dep = dep; - } + public ITestInterface Dep { get; } = dep; } - public class ClassWithMultipleDependencies + public class ClassWithMultipleDependencies(ITestInterface testInterfaceDep, ClassWithDependency classWithDependencyDep) { - public ITestInterface TestInterfaceDep { get; } - public ClassWithDependency ClassWithDependencyDep { get; } - - public ClassWithMultipleDependencies(ITestInterface testInterfaceDep, ClassWithDependency classWithDependencyDep) - { - TestInterfaceDep = testInterfaceDep; - ClassWithDependencyDep = classWithDependencyDep; - } + public ITestInterface TestInterfaceDep { get; } = testInterfaceDep; + public ClassWithDependency ClassWithDependencyDep { get; } = classWithDependencyDep; } - public class TestImplDecorator : ITestInterface + public class TestImplDecorator(ITestInterface inner) : ITestInterface { - public ITestInterface Inner { get; } - - public TestImplDecorator(ITestInterface inner) - { - Inner = inner; - } + public ITestInterface Inner { get; } = inner; } } \ No newline at end of file diff --git a/tests/NSubstitute.Acceptance.Specs/OutAndRefParameters.cs b/tests/NSubstitute.Acceptance.Specs/OutAndRefParameters.cs index d440db4b..983a469d 100644 --- a/tests/NSubstitute.Acceptance.Specs/OutAndRefParameters.cs +++ b/tests/NSubstitute.Acceptance.Specs/OutAndRefParameters.cs @@ -249,14 +249,12 @@ public void Exception_message_displays_original_values() StringAssert.Contains("12345", exception.Message); } - private class Something + private class Something(ILookupStrings lookup) { - private readonly ILookupStrings _lookup; - public Something(ILookupStrings lookup) { _lookup = lookup; } public string GetValue(string key) { string value; - return _lookup.TryGet(key, out value) ? value : "none"; + return lookup.TryGet(key, out value) ? value : "none"; } } } diff --git a/tests/NSubstitute.Acceptance.Specs/PartialSubExamples.cs b/tests/NSubstitute.Acceptance.Specs/PartialSubExamples.cs index 3e643679..4348567f 100644 --- a/tests/NSubstitute.Acceptance.Specs/PartialSubExamples.cs +++ b/tests/NSubstitute.Acceptance.Specs/PartialSubExamples.cs @@ -87,18 +87,15 @@ public class TaskList public virtual string[] ToArray() { return [.. list]; } } - public class TaskView + public class TaskView(TaskList tasks) { - private readonly TaskList _tasks; public string TaskEntryField { get; set; } public string[] DisplayedTasks { get; set; } - public TaskView(TaskList tasks) { _tasks = tasks; } - public void ClickButton() { - _tasks.Add(TaskEntryField); - DisplayedTasks = _tasks.ToArray(); + tasks.Add(TaskEntryField); + DisplayedTasks = tasks.ToArray(); } } diff --git a/tests/NSubstitute.Acceptance.Specs/ReturnsForAll.cs b/tests/NSubstitute.Acceptance.Specs/ReturnsForAll.cs index a5f0997b..994fc576 100644 --- a/tests/NSubstitute.Acceptance.Specs/ReturnsForAll.cs +++ b/tests/NSubstitute.Acceptance.Specs/ReturnsForAll.cs @@ -15,8 +15,8 @@ public void SetUp() { _fluentSomething = Substitute.For(); _something = Substitute.For(); - _fluentSomething.ReturnsForAll(_fluentSomething); - _fluentSomething.ReturnsForAll(_something); + _fluentSomething.ReturnsForAll(_fluentSomething); + _fluentSomething.ReturnsForAll(_something); } [Test] diff --git a/tests/NSubstitute.Acceptance.Specs/ReturnsForAllFromFunc.cs b/tests/NSubstitute.Acceptance.Specs/ReturnsForAllFromFunc.cs index ef16be14..a029fceb 100644 --- a/tests/NSubstitute.Acceptance.Specs/ReturnsForAllFromFunc.cs +++ b/tests/NSubstitute.Acceptance.Specs/ReturnsForAllFromFunc.cs @@ -15,8 +15,8 @@ public void SetUp() { _fluentSomething = Substitute.For(); _something = Substitute.For(); - _fluentSomething.ReturnsForAll(ci => _fluentSomething); - _fluentSomething.ReturnsForAll(ci => _something); + _fluentSomething.ReturnsForAll(ci => _fluentSomething); + _fluentSomething.ReturnsForAll(ci => _something); } [Test] diff --git a/tests/NSubstitute.Acceptance.Specs/SubbingForConcreteTypesAndMultipleInterfaces.cs b/tests/NSubstitute.Acceptance.Specs/SubbingForConcreteTypesAndMultipleInterfaces.cs index c12e2eca..26d4d778 100644 --- a/tests/NSubstitute.Acceptance.Specs/SubbingForConcreteTypesAndMultipleInterfaces.cs +++ b/tests/NSubstitute.Acceptance.Specs/SubbingForConcreteTypesAndMultipleInterfaces.cs @@ -90,10 +90,8 @@ public class Partial public virtual int Number() { return -1; } public int GetNumberPlusOne() { return Number() + 1; } } - public abstract class ClassWithCtorArgs + public abstract class ClassWithCtorArgs(string s, int a) { - public ClassWithCtorArgs(string s, int a) { StringFromCtorArg = s; IntFromCtorArg = a; } - public string StringFromCtorArg { get; set; } - public int IntFromCtorArg { get; set; } + public string StringFromCtorArg { get; set; } = s; public int IntFromCtorArg { get; set; } = a; } } \ No newline at end of file