diff --git a/.editorconfig b/.editorconfig
index 84059808..840e3c38 100644
--- a/.editorconfig
+++ b/.editorconfig
@@ -17,7 +17,9 @@ dotnet_style_qualification_for_field = false:suggestion
dotnet_style_qualification_for_property = false:suggestion
dotnet_style_qualification_for_method = false:suggestion
dotnet_style_qualification_for_event = false:suggestion
-csharp_style_namespace_declarations=file_scoped:warning
+csharp_style_namespace_declarations = file_scoped:warning
+dotnet_style_prefer_collection_expression = true:warning
+dotnet_style_collection_initializer = true:warning
# ReSharper properties
resharper_int_align_switch_expressions = true
diff --git a/src/NSubstitute/Compatibility/DiagnosticsNullabilityAttributes.cs b/src/NSubstitute/Compatibility/DiagnosticsNullabilityAttributes.cs
index a016b1f3..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.
@@ -90,7 +82,7 @@ internal sealed class MemberNotNullAttribute : Attribute
///
/// The field or property member that is promised to be not-null.
///
- public MemberNotNullAttribute(string member) => Members = new[] { member };
+ public MemberNotNullAttribute(string member) => Members = [member];
/// Initializes the attribute with the list of field and property members.
///
@@ -116,7 +108,7 @@ internal sealed class MemberNotNullWhenAttribute : Attribute
public MemberNotNullWhenAttribute(bool returnValue, string member)
{
ReturnValue = returnValue;
- Members = new[] { member };
+ Members = [member];
}
/// Initializes the attribute with the specified return value condition and list of field and property members.
diff --git a/src/NSubstitute/Core/ArgumentSpecificationDequeue.cs b/src/NSubstitute/Core/ArgumentSpecificationDequeue.cs
index 0c251d6d..81e6d481 100644
--- a/src/NSubstitute/Core/ArgumentSpecificationDequeue.cs
+++ b/src/NSubstitute/Core/ArgumentSpecificationDequeue.cs
@@ -3,16 +3,9 @@
namespace NSubstitute.Core;
-public class ArgumentSpecificationDequeue : IArgumentSpecificationDequeue
+public class ArgumentSpecificationDequeue(Func> dequeueAllQueuedArgSpecs) : IArgumentSpecificationDequeue
{
- private static readonly IArgumentSpecification[] EmptySpecifications = new IArgumentSpecification[0];
-
- private readonly Func> _dequeueAllQueuedArgSpecs;
-
- public ArgumentSpecificationDequeue(Func> dequeueAllQueuedArgSpecs)
- {
- _dequeueAllQueuedArgSpecs = dequeueAllQueuedArgSpecs;
- }
+ private static readonly IArgumentSpecification[] EmptySpecifications = [];
public IList DequeueAllArgumentSpecificationsForMethod(int parametersCount)
{
@@ -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 cfeb2555..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)
{
@@ -31,7 +26,7 @@ public bool IsSatisfiedBy(object? argument)
public string Format(object? argument, bool highlight)
{
- var argArray = argument is IEnumerable enumerableArgs ? enumerableArgs.Cast().ToArray() : new object[0];
+ var argArray = argument is IEnumerable enumerableArgs ? enumerableArgs.Cast().ToArray() : [];
return Format(argArray, _argumentSpecifications).Join(", ");
}
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/Call.cs b/src/NSubstitute/Core/Call.cs
index 4bf09424..affd4f56 100644
--- a/src/NSubstitute/Core/Call.cs
+++ b/src/NSubstitute/Core/Call.cs
@@ -81,7 +81,7 @@ public void AssignSequenceNumber(long number)
object?[] originalArray = _originalArguments;
if (originalArray == _arguments && originalArray.Length > 0)
{
- object?[] copy = originalArray.ToArray();
+ object?[] copy = [.. originalArray];
// If it happens that _originalArguments doesn't point to the `_arguments` anymore -
// it might happen that other thread already created a copy and mutated the original `_arguments` array.
// In this case it's unsafe to replace it with a copy.
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)
{
@@ -77,7 +70,7 @@ internal static bool TypesAreAllEquivalent(Type[] aArgs, Type[] bArgs)
if (first.IsGenericType && second.IsGenericType
&& first.GetGenericTypeDefinition() == second.GetGenericTypeDefinition())
{
- // both are the same generic type. If their GenericTypeArguments match then they are equivalent
+ // both are the same generic type. If their GenericTypeArguments match then they are equivalent
if (!TypesAreAllEquivalent(first.GenericTypeArguments, second.GenericTypeArguments))
{
return false;
@@ -85,8 +78,13 @@ internal static bool TypesAreAllEquivalent(Type[] aArgs, Type[] bArgs)
continue;
}
- var areEquivalent = first.IsAssignableFrom(second) || second.IsAssignableFrom(first) ||
- typeof(Arg.AnyType).IsAssignableFrom(first) || typeof(Arg.AnyType).IsAssignableFrom(second);
+ var areAssignable = first.IsAssignableFrom(second) || second.IsAssignableFrom(first);
+ var areAnyTypeAssignable = typeof(Arg.AnyType).IsAssignableFrom(first) ||
+ typeof(Arg.AnyType).IsAssignableFrom(second);
+ var areByRefAnyTypeAssignable = first.IsByRef && second.IsByRef &&
+ (typeof(Arg.AnyType).IsAssignableFrom(first.GetElementType()) ||
+ typeof(Arg.AnyType).IsAssignableFrom(second.GetElementType()));
+ var areEquivalent = areAssignable || areAnyTypeAssignable || areByRefAnyTypeAssignable;
if (!areEquivalent) return false;
}
return true;
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 882e8aa5..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 = new();
- private readonly ISubstituteState _substituteState;
+ private readonly List _handlers = [];
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 1d519ecb..db90cccf 100644
--- a/src/NSubstitute/Core/DependencyInjection/NSubContainer.cs
+++ b/src/NSubstitute/Core/DependencyInjection/NSubContainer.cs
@@ -17,7 +17,7 @@ public class NSubContainer : IConfigurableNSubContainer
{
private readonly NSubContainer? _parentContainer;
private readonly object _syncRoot;
- private readonly Dictionary _registrations = new();
+ private readonly Dictionary _registrations = [];
public NSubContainer()
{
@@ -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 = new Dictionary();
- private readonly NSubContainer _mostNestedContainer;
-
- public Scope(NSubContainer mostNestedContainer)
- {
- _mostNestedContainer = mostNestedContainer;
- }
+ private readonly Dictionary _cache = [];
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/EventHandlerRegistry.cs b/src/NSubstitute/Core/EventHandlerRegistry.cs
index 82485927..1309f912 100644
--- a/src/NSubstitute/Core/EventHandlerRegistry.cs
+++ b/src/NSubstitute/Core/EventHandlerRegistry.cs
@@ -6,7 +6,7 @@ public class EventHandlerRegistry : IEventHandlerRegistry
// Events are not expected to be configured/raised concurrently, so simple locking should be sufficient.
// List lookup is O(n), but for really small size performance is comparable to dictionary.
// Given that normally a few events are configured only, it should be totally fine.
- private readonly List>> _handlersForEvent = new();
+ private readonly List>> _handlersForEvent = [];
public void Add(string eventName, object handler)
{
diff --git a/src/NSubstitute/Core/Events/DelegateEventWrapper.cs b/src/NSubstitute/Core/Events/DelegateEventWrapper.cs
index f2bfb372..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,22 +43,22 @@ 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 new[] { sender, eventArgs };
+ return [sender, eventArgs];
}
private static bool RequiredArgsHaveBeenProvided(object?[] providedArgs, ParameterInfo[] requiredArgs)
diff --git a/src/NSubstitute/Core/Events/EventHandlerWrapper.cs b/src/NSubstitute/Core/Events/EventHandlerWrapper.cs
index 767784b9..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)
@@ -35,6 +29,6 @@ protected override object[] WorkOutRequiredArguments(ICall call)
{
var sender = _sender ?? call.Target();
var eventArgs = _eventArgs ?? GetDefaultForEventArgType(typeof(TEventArgs));
- return new[] { sender, eventArgs };
+ return [sender, eventArgs];
}
}
\ No newline at end of file
diff --git a/src/NSubstitute/Core/Events/RaiseEventWrapper.cs b/src/NSubstitute/Core/Events/RaiseEventWrapper.cs
index 4b762b7d..efe56e1c 100644
--- a/src/NSubstitute/Core/Events/RaiseEventWrapper.cs
+++ b/src/NSubstitute/Core/Events/RaiseEventWrapper.cs
@@ -21,7 +21,7 @@ protected EventArgs GetDefaultForEventArgType(Type type)
, type.Name, RaiseMethodName);
throw new CannotCreateEventArgsException(message);
}
- return (EventArgs)defaultConstructor.Invoke(new object[0]);
+ return (EventArgs)defaultConstructor.Invoke([]);
}
private static ConstructorInfo? GetDefaultConstructor(Type type) => type.GetConstructor(Type.EmptyTypes);
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 81b76a57..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 = new();
+ 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/ReflectionExtensions.cs b/src/NSubstitute/Core/ReflectionExtensions.cs
index 96292774..4672f34f 100644
--- a/src/NSubstitute/Core/ReflectionExtensions.cs
+++ b/src/NSubstitute/Core/ReflectionExtensions.cs
@@ -41,8 +41,6 @@ private static bool CanBePropertySetterCall(MethodInfo call)
private static PropertyInfo[] GetAllProperties(Type? type)
{
- return type != null
- ? type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
- : new PropertyInfo[0];
+ return type?.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) ?? [];
}
}
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 8a9f6388..f021ae28 100644
--- a/src/NSubstitute/Core/SubstituteFactory.cs
+++ b/src/NSubstitute/Core/SubstituteFactory.cs
@@ -5,18 +5,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.
@@ -50,15 +40,15 @@ public object CreatePartial(Type[] typesToProxy, object?[] constructorArguments)
private object Create(Type[] typesToProxy, object?[] constructorArguments, bool callBaseByDefault, bool isPartial)
{
- 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, isPartial, 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 59756f52..73e1100b 100644
--- a/src/NSubstitute/Core/ThreadLocalContext.cs
+++ b/src/NSubstitute/Core/ThreadLocalContext.cs
@@ -6,7 +6,7 @@ namespace NSubstitute.Core;
public class ThreadLocalContext : IThreadLocalContext
{
- private static readonly IArgumentSpecification[] EmptySpecifications = new IArgumentSpecification[0];
+ private static readonly IArgumentSpecification[] EmptySpecifications = [];
private readonly RobustThreadLocal _lastCallRouter;
private readonly RobustThreadLocal> _argumentSpecifications;
@@ -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/ExceptionExtensions.cs b/src/NSubstitute/Extensions/ExceptionExtensions.cs
index ced66769..d9ad6731 100644
--- a/src/NSubstitute/Extensions/ExceptionExtensions.cs
+++ b/src/NSubstitute/Extensions/ExceptionExtensions.cs
@@ -236,7 +236,7 @@ private static object FromException(object value, Exception exception)
{
var fromExceptionMethodInfo = typeof(Task).GetMethods(BindingFlags.Static | BindingFlags.Public).Single(m => m.Name == "FromException" && m.ContainsGenericParameters);
var specificFromExceptionMethod = fromExceptionMethodInfo.MakeGenericMethod(valueType.GenericTypeArguments);
- return specificFromExceptionMethod.Invoke(null, new object[] { exception });
+ return specificFromExceptionMethod.Invoke(null, [exception]);
}
return Task.FromException(exception);
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 4faa1e11..ccc5d437 100644
--- a/src/NSubstitute/Proxies/CastleDynamicProxy/CastleDynamicProxyFactory.cs
+++ b/src/NSubstitute/Proxies/CastleDynamicProxy/CastleDynamicProxyFactory.cs
@@ -9,20 +9,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, bool isPartial, object?[]? constructorArguments)
{
@@ -44,7 +34,7 @@ private object GenerateTypeProxy(ICallRouter callRouter, Type typeToProxy, Type[
typeToProxy,
additionalInterfaces,
constructorArguments,
- new IInterceptor[] { proxyIdInterceptor, forwardingInterceptor },
+ [proxyIdInterceptor, forwardingInterceptor],
proxyGenerationOptions,
isPartial);
@@ -68,7 +58,7 @@ private object GenerateDelegateProxy(ICallRouter callRouter, Type delegateType,
typeToProxy: typeof(object),
additionalInterfaces: null,
constructorArguments: null,
- interceptors: new IInterceptor[] { proxyIdInterceptor, forwardingInterceptor },
+ interceptors: [proxyIdInterceptor, forwardingInterceptor],
proxyGenerationOptions,
isPartial: false);
@@ -83,8 +73,8 @@ private CastleForwardingInterceptor CreateForwardingInterceptor(ICallRouter call
{
return new CastleForwardingInterceptor(
new CastleInvocationMapper(
- _callFactory,
- _argSpecificationDequeue),
+ callFactory,
+ argSpecificationDequeue),
callRouter);
}
@@ -238,15 +228,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 5b42b22d..a43600eb 100644
--- a/src/NSubstitute/Proxies/CastleDynamicProxy/CastleInvocationMapper.cs
+++ b/src/NSubstitute/Proxies/CastleDynamicProxy/CastleInvocationMapper.cs
@@ -4,17 +4,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 bc40a736..00281314 100644
--- a/src/NSubstitute/Proxies/DelegateProxy/DelegateProxyFactory.cs
+++ b/src/NSubstitute/Proxies/DelegateProxy/DelegateProxyFactory.cs
@@ -5,14 +5,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, bool isPartial, 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 dbcab907..e6efd4a1 100644
--- a/src/NSubstitute/Proxies/ProxyFactory.cs
+++ b/src/NSubstitute/Proxies/ProxyFactory.cs
@@ -5,22 +5,14 @@
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, bool isPartial, object?[]? constructorArguments)
{
var isDelegate = typeToProxy.IsDelegate();
return isDelegate
- ? _delegateFactory.GenerateProxy(callRouter, typeToProxy, additionalInterfaces, isPartial, constructorArguments)
- : _dynamicProxyFactory.GenerateProxy(callRouter, typeToProxy, additionalInterfaces, isPartial, constructorArguments);
+ ? delegateFactory.GenerateProxy(callRouter, typeToProxy, additionalInterfaces, isPartial, constructorArguments)
+ : dynamicProxyFactory.GenerateProxy(callRouter, typeToProxy, additionalInterfaces, isPartial, constructorArguments);
}
}
\ No newline at end of file
diff --git a/src/NSubstitute/Raise.cs b/src/NSubstitute/Raise.cs
index f0fc2580..d247db62 100644
--- a/src/NSubstitute/Raise.cs
+++ b/src/NSubstitute/Raise.cs
@@ -81,7 +81,7 @@ private static object[] FixParamsArrayAmbiguity(object[] arguments, Type delegat
if (singleParameterType.IsInstanceOfType(arguments))
{
- return new object[] { arguments };
+ return [arguments];
}
return arguments;
diff --git a/src/NSubstitute/Routing/AutoValues/AutoObservableProvider.cs b/src/NSubstitute/Routing/AutoValues/AutoObservableProvider.cs
index bdf1ecd0..713a5bde 100644
--- a/src/NSubstitute/Routing/AutoValues/AutoObservableProvider.cs
+++ b/src/NSubstitute/Routing/AutoValues/AutoObservableProvider.cs
@@ -1,17 +1,10 @@
-using System.Reflection;
-using NSubstitute.Core;
+using NSubstitute.Core;
+using System.Reflection;
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,11 +14,9 @@ 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)
- , new object?[] { value });
+ return Activator.CreateInstance(typeof(ReturnObservable<>).MakeGenericType(innerType), [value]);
}
private static object? GetDefault(Type type)
diff --git a/src/NSubstitute/Routing/AutoValues/AutoSubstituteProvider.cs b/src/NSubstitute/Routing/AutoValues/AutoSubstituteProvider.cs
index e3806e1d..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(new[] { type }, new object[0]);
+ 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 239b6506..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,12 +14,12 @@ 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);
var taskCompletionSource = Activator.CreateInstance(taskCompletionSourceType);
- taskCompletionSourceType.GetMethod(nameof(TaskCompletionSource.SetResult))!.Invoke(taskCompletionSource, new[] { value });
+ taskCompletionSourceType.GetMethod(nameof(TaskCompletionSource.SetResult))!.Invoke(taskCompletionSource, [value]);
return taskCompletionSourceType.GetProperty(nameof(TaskCompletionSource.Task))!.GetValue(taskCompletionSource, null)!;
}
else
diff --git a/src/NSubstitute/Routing/AutoValues/AutoValueProvidersFactory.cs b/src/NSubstitute/Routing/AutoValues/AutoValueProvidersFactory.cs
index 815c41c0..5dc7fe7c 100644
--- a/src/NSubstitute/Routing/AutoValues/AutoValueProvidersFactory.cs
+++ b/src/NSubstitute/Routing/AutoValues/AutoValueProvidersFactory.cs
@@ -12,15 +12,15 @@ public IReadOnlyCollection CreateProviders(ISubstituteFactor
() => result ?? throw new SubstituteInternalException("Value was not constructed yet."),
LazyThreadSafetyMode.PublicationOnly);
- result = new IAutoValueProvider[]
- {
+ result =
+ [
new AutoObservableProvider(lazyResult),
new AutoQueryableProvider(),
new AutoSubstituteProvider(substituteFactory),
new AutoStringProvider(),
new AutoArrayProvider(),
new AutoTaskProvider(lazyResult)
- };
+ ];
return result;
}
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 ac84ed24..a89e3d5e 100644
--- a/src/NSubstitute/Routing/RouteFactory.cs
+++ b/src/NSubstitute/Routing/RouteFactory.cs
@@ -4,112 +4,95 @@
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 ICallHandler[] {
- new ClearUnusedCallSpecHandler(_threadLocalContext.PendingSpecification)
- , new AddCallToQueryResultHandler(_threadLocalContext)
- , new ReturnAutoValue(AutoValueBehaviour.UseValueForSubsequentCalls, state.AutoValueProviders, state.AutoValuesCallResults, _callSpecificationFactory)
- , ReturnDefaultForReturnTypeHandler()
- });
+ return new Route([
+ 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 ICallHandler[] {
- 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()
- });
+ 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),
+ ReturnDefaultForReturnTypeHandler()
+ ]);
}
public IRoute DoWhenCalled(ISubstituteState state, Action doAction, MatchArgs matchArgs)
{
- return new Route(new ICallHandler[] {
- new ClearLastCallRouterHandler(_threadLocalContext)
- , new ClearUnusedCallSpecHandler(_threadLocalContext.PendingSpecification)
- , new SetActionForCallHandler(_callSpecificationFactory, state.CallActions, doAction, matchArgs)
- , ReturnDefaultForReturnTypeHandler()
- });
+ return new Route([
+ 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 ICallHandler[] {
- new ClearLastCallRouterHandler(_threadLocalContext)
- , new ClearUnusedCallSpecHandler(_threadLocalContext.PendingSpecification)
- , new DoNotCallBaseForCallHandler(_callSpecificationFactory, state.CallBaseConfiguration, matchArgs)
- , ReturnDefaultForReturnTypeHandler()
- });
+ return new Route([
+ 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 ICallHandler[] {
- new ClearLastCallRouterHandler(_threadLocalContext)
- , new ClearUnusedCallSpecHandler(_threadLocalContext.PendingSpecification)
- , new CallBaseForCallHandler(_callSpecificationFactory, state.CallBaseConfiguration, matchArgs)
- , ReturnDefaultForReturnTypeHandler()
- });
+ return new Route([
+ 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 ICallHandler[] {
- new ClearLastCallRouterHandler(_threadLocalContext)
- , new ClearUnusedCallSpecHandler(_threadLocalContext.PendingSpecification)
- , new RaiseEventHandler(state.EventHandlerRegistry, getEventArguments)
- , ReturnDefaultForReturnTypeHandler()
- });
+ return new Route([
+ new ClearLastCallRouterHandler(threadLocalContext),
+ new ClearUnusedCallSpecHandler(threadLocalContext.PendingSpecification),
+ new RaiseEventHandler(state.EventHandlerRegistry, getEventArguments),
+ ReturnDefaultForReturnTypeHandler()
+ ]);
}
public IRoute RecordCallSpecification(ISubstituteState state)
{
- return new Route(new ICallHandler[] {
- 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()
- });
+ 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 ReturnFromAndConfigureDynamicCall(state.ConfigureCall),
+ ReturnDefaultForReturnTypeHandler()
+ ]);
}
public IRoute RecordReplay(ISubstituteState state)
{
- return new Route(new ICallHandler[] {
- new TrackLastCallHandler(_threadLocalContext.PendingSpecification)
- , new RecordCallHandler(state.ReceivedCalls, _sequenceNumberGenerator)
- , new EventSubscriptionHandler(state.EventHandlerRegistry)
- , 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 ReturnFromAndConfigureDynamicCall(state.ConfigureCall)
- , ReturnDefaultForReturnTypeHandler()
- });
+ return new Route([
+ new TrackLastCallHandler(threadLocalContext.PendingSpecification),
+ new RecordCallHandler(state.ReceivedCalls, sequenceNumberGenerator),
+ new EventSubscriptionHandler(state.EventHandlerRegistry),
+ 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 ReturnFromAndConfigureDynamicCall(state.ConfigureCall),
+ ReturnDefaultForReturnTypeHandler()
+ ]);
}
- private ReturnDefaultForReturnTypeHandler ReturnDefaultForReturnTypeHandler() => new(_defaultForType);
+ private ReturnDefaultForReturnTypeHandler ReturnDefaultForReturnTypeHandler() => new(defaultForType);
}
\ No newline at end of file
diff --git a/src/NSubstitute/Substitute.cs b/src/NSubstitute/Substitute.cs
index 7d651a10..729fd2c0 100644
--- a/src/NSubstitute/Substitute.cs
+++ b/src/NSubstitute/Substitute.cs
@@ -22,7 +22,7 @@ public static class Substitute
public static T For(params object[] constructorArguments)
where T : class
{
- return (T)For(new[] { typeof(T) }, constructorArguments);
+ return (T)For([typeof(T)], constructorArguments);
}
///
@@ -38,7 +38,7 @@ public static T1 For(params object[] constructorArguments)
where T1 : class
where T2 : class
{
- return (T1)For(new[] { typeof(T1), typeof(T2) }, constructorArguments);
+ return (T1)For([typeof(T1), typeof(T2)], constructorArguments);
}
///
@@ -57,7 +57,7 @@ public static T1 For(params object[] constructorArguments)
where T2 : class
where T3 : class
{
- return (T1)For(new[] { typeof(T1), typeof(T2), typeof(T3) }, constructorArguments);
+ return (T1)For([typeof(T1), typeof(T2), typeof(T3)], constructorArguments);
}
///
@@ -88,7 +88,7 @@ public static T ForPartsOf(params object[] constructorArguments)
where T : class
{
var substituteFactory = SubstitutionContext.Current.SubstituteFactory;
- return (T)substituteFactory.CreatePartial(new[] { typeof(T) }, constructorArguments);
+ return (T)substituteFactory.CreatePartial([typeof(T)], constructorArguments);
}
public static T ForTypeForwardingTo(params object[] constructorArguments)
diff --git a/src/NSubstitute/SubstituteExtensions.Returns.cs b/src/NSubstitute/SubstituteExtensions.Returns.cs
index e63b673d..39ecb82e 100644
--- a/src/NSubstitute/SubstituteExtensions.Returns.cs
+++ b/src/NSubstitute/SubstituteExtensions.Returns.cs
@@ -54,7 +54,7 @@ private static ConfiguredCall ConfigureReturn(MatchArgs matchArgs, T? returnT
}
else
{
- returnValue = new ReturnMultipleValues(new[] { returnThis }.Concat(returnThese).ToArray());
+ returnValue = new ReturnMultipleValues([returnThis, .. returnThese]);
}
return SubstitutionContext
.Current
@@ -71,7 +71,7 @@ private static ConfiguredCall ConfigureReturn(MatchArgs matchArgs, Func(new[] { returnThis }.Concat(returnThese).ToArray());
+ returnValue = new ReturnMultipleFuncsValues([returnThis, .. returnThese]);
}
return SubstitutionContext
diff --git a/tests/NSubstitute.Acceptance.Specs/ArgumentMatching.cs b/tests/NSubstitute.Acceptance.Specs/ArgumentMatching.cs
index 63468c3d..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();
}
@@ -200,7 +200,7 @@ public void Received_should_compare_elements_for_params_arguments()
_something.Received().WithParams(1, first, second);
_something.Received().WithParams(1, Arg.Any(), second);
_something.Received().WithParams(1, first, Arg.Any());
- _something.Received().WithParams(1, new[] { first, second });
+ _something.Received().WithParams(1, [first, second]);
_something.Received().WithParams(1, Arg.Any());
_something.Received().WithParams(1, Arg.Is(x => x.Length == 2));
_something.DidNotReceive().WithParams(2, first, second);
diff --git a/tests/NSubstitute.Acceptance.Specs/ArgumentMatchingCompat.cs b/tests/NSubstitute.Acceptance.Specs/ArgumentMatchingCompat.cs
index 08f68aad..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();
}
@@ -141,7 +141,7 @@ public void Received_should_compare_elements_for_params_arguments()
_something.Received().WithParams(1, first, second);
_something.Received().WithParams(1, Arg.Compat.Any(), second);
_something.Received().WithParams(1, first, Arg.Compat.Any());
- _something.Received().WithParams(1, new[] { first, second });
+ _something.Received().WithParams(1, [first, second]);
_something.Received().WithParams(1, Arg.Compat.Any());
_something.Received().WithParams(1, Arg.Compat.Is(x => x.Length == 2));
_something.DidNotReceive().WithParams(2, first, second);
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 91b49d1b..bc2c0d8e 100644
--- a/tests/NSubstitute.Acceptance.Specs/EventRaising.cs
+++ b/tests/NSubstitute.Acceptance.Specs/EventRaising.cs
@@ -336,8 +336,7 @@ 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) { }
}
}
\ No newline at end of file
diff --git a/tests/NSubstitute.Acceptance.Specs/FieldReports/ExceptionsThrownFromCustomArgumentMatchers.cs b/tests/NSubstitute.Acceptance.Specs/FieldReports/ExceptionsThrownFromCustomArgumentMatchers.cs
index 8ef1126d..79b6d9dd 100644
--- a/tests/NSubstitute.Acceptance.Specs/FieldReports/ExceptionsThrownFromCustomArgumentMatchers.cs
+++ b/tests/NSubstitute.Acceptance.Specs/FieldReports/ExceptionsThrownFromCustomArgumentMatchers.cs
@@ -81,10 +81,10 @@ public void Multiple_conditions_where_one_requires_an_array_index_available()
{
var emptyArray = new string[0];
var request = Substitute.For();
- request.GetMultiple(Arg.Is(x => x[0] == "greeting")).Returns(new[] { "hello", "bye" });
- request.GetMultiple(emptyArray).Returns(new[] { "?" });
+ request.GetMultiple(Arg.Is(x => x[0] == "greeting")).Returns(["hello", "bye"]);
+ request.GetMultiple(emptyArray).Returns(["?"]);
- Assert.That(request.GetMultiple(new[] { "greeting" }), Is.EqualTo(new[] { "hello", "bye" }));
+ Assert.That(request.GetMultiple(["greeting"]), Is.EqualTo(new[] { "hello", "bye" }));
Assert.That(request.GetMultiple(emptyArray), Is.EqualTo(new[] { "?" }));
}
}
\ No newline at end of file
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/Issue47_RaisingEventsWithNullArg.cs b/tests/NSubstitute.Acceptance.Specs/FieldReports/Issue47_RaisingEventsWithNullArg.cs
index 78b9fa23..a4953be6 100644
--- a/tests/NSubstitute.Acceptance.Specs/FieldReports/Issue47_RaisingEventsWithNullArg.cs
+++ b/tests/NSubstitute.Acceptance.Specs/FieldReports/Issue47_RaisingEventsWithNullArg.cs
@@ -23,6 +23,6 @@ public void Pass_null_when_raising_delegate_event()
public void Pass_null_when_raising_eventhandlerish_event()
{
var sub = Substitute.For();
- sub.OnEventishThing += Raise.Event(new object[] { null });
+ sub.OnEventishThing += Raise.Event([null]);
}
}
\ No newline at end of file
diff --git a/tests/NSubstitute.Acceptance.Specs/FieldReports/Issue500_SpecialMethodsWithoutAttribute.cs b/tests/NSubstitute.Acceptance.Specs/FieldReports/Issue500_SpecialMethodsWithoutAttribute.cs
index 7a52bc71..089e5f71 100644
--- a/tests/NSubstitute.Acceptance.Specs/FieldReports/Issue500_SpecialMethodsWithoutAttribute.cs
+++ b/tests/NSubstitute.Acceptance.Specs/FieldReports/Issue500_SpecialMethodsWithoutAttribute.cs
@@ -18,7 +18,7 @@ static Issue500_SpecialMethodsWithoutAttribute()
[Test]
public void ShouldCorrectlyConfigureProperty()
{
- var substitute = Substitute.For(new[] { TypeWithMissingSpecialNameMethodAttributes }, new object[0]);
+ var substitute = Substitute.For([TypeWithMissingSpecialNameMethodAttributes], []);
var fixture = new GeneratedTypeFixture(substitute);
fixture.MyProperty = "42";
@@ -30,7 +30,7 @@ public void ShouldCorrectlyConfigureProperty()
[Test]
public void ShouldCorrectlyConfigureEvent()
{
- object substitute = Substitute.For(new[] { TypeWithMissingSpecialNameMethodAttributes }, new object[0]);
+ object substitute = Substitute.For([TypeWithMissingSpecialNameMethodAttributes], []);
var fixture = new GeneratedTypeFixture(substitute);
bool wasCalled = false;
@@ -58,13 +58,13 @@ private static Type GenerateTypeWithMissingSpecialNameAttributes()
MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.Abstract |
MethodAttributes.HideBySig | MethodAttributes.NewSlot /* | MethodAttributes.SpecialName */,
typeof(void),
- new[] { typeof(EventHandler) });
+ [typeof(EventHandler)]);
var evRemover = typeBuilder.DefineMethod(
$"remove_{EventName}",
MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.Abstract |
MethodAttributes.HideBySig | MethodAttributes.NewSlot /* | MethodAttributes.SpecialName */,
typeof(void),
- new[] { typeof(EventHandler) });
+ [typeof(EventHandler)]);
evBuilder.SetAddOnMethod(evAdder);
evBuilder.SetRemoveOnMethod(evRemover);
@@ -81,32 +81,25 @@ private static Type GenerateTypeWithMissingSpecialNameAttributes()
MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.Abstract |
MethodAttributes.HideBySig | MethodAttributes.NewSlot /* | MethodAttributes.SpecialName */,
typeof(void),
- new[] { typeof(object) });
+ [typeof(object)]);
propBuilder.SetGetMethod(propGetter);
propBuilder.SetSetMethod(propSetter);
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 21076ff5..ab16bf42 100644
--- a/tests/NSubstitute.Acceptance.Specs/FieldReports/Issue560_RaiseEventWithArrayArg.cs
+++ b/tests/NSubstitute.Acceptance.Specs/FieldReports/Issue560_RaiseEventWithArrayArg.cs
@@ -56,7 +56,7 @@ public void Should_raise_event_for_object_array_arg_provided_without_using_param
var eventSamples = Substitute.For();
eventSamples.ActionWithParamOfObjectArray += x => capturedArg = x;
- eventSamples.ActionWithParamOfObjectArray += Raise.Event>(new object[] { arg1 });
+ eventSamples.ActionWithParamOfObjectArray += Raise.Event>([arg1]);
Assert.That(capturedArg, Is.EqualTo(arg1));
}
@@ -69,7 +69,7 @@ public void Should_raise_event_for_object_array_arg_provided_without_using_param
var eventSamples = Substitute.For();
eventSamples.ActionWithParamOfObjectArray += x => capturedArg = x;
- eventSamples.ActionWithParamOfObjectArray += Raise.Event>(new object[] { arg1 });
+ eventSamples.ActionWithParamOfObjectArray += Raise.Event>([arg1]);
Assert.That(capturedArg, Is.EqualTo(arg1));
}
@@ -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/FormattingCallsWhenThrowingReceivedCallsExceptions.cs b/tests/NSubstitute.Acceptance.Specs/FormattingCallsWhenThrowingReceivedCallsExceptions.cs
index 5fea58f9..70a72a0b 100644
--- a/tests/NSubstitute.Acceptance.Specs/FormattingCallsWhenThrowingReceivedCallsExceptions.cs
+++ b/tests/NSubstitute.Acceptance.Specs/FormattingCallsWhenThrowingReceivedCallsExceptions.cs
@@ -265,7 +265,7 @@ public class When_checking_call_to_method_with_params : Context
protected override void ConfigureContext()
{
Sample.ParamsMethod(2, "hello", "everybody");
- Sample.ParamsMethod(1, new[] { "hello", "everybody" });
+ Sample.ParamsMethod(1, ["hello", "everybody"]);
Sample.ParamsMethod(1, "hello");
Sample.ParamsMethod(3, "1", "2", "3");
Sample.ParamsMethod(1);
@@ -298,7 +298,7 @@ public class When_checking_call_to_method_with_valuetype_params : Context
protected override void ConfigureContext()
{
Sample.IntParamsMethod(1, 2, 3);
- Sample.IntParamsMethod(new[] { 4, 5 });
+ Sample.IntParamsMethod([4, 5]);
Sample.IntParamsMethod();
}
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 dee80035..4348567f 100644
--- a/tests/NSubstitute.Acceptance.Specs/PartialSubExamples.cs
+++ b/tests/NSubstitute.Acceptance.Specs/PartialSubExamples.cs
@@ -82,23 +82,20 @@ public class UnderlyingListExample
{
public class TaskList
{
- readonly List list = new List();
+ readonly List list = [];
public virtual void Add(string s) { list.Add(s); }
- public virtual string[] ToArray() { return list.ToArray(); }
+ 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/ReceivedCalls.cs b/tests/NSubstitute.Acceptance.Specs/ReceivedCalls.cs
index cbc74635..4a664d9d 100644
--- a/tests/NSubstitute.Acceptance.Specs/ReceivedCalls.cs
+++ b/tests/NSubstitute.Acceptance.Specs/ReceivedCalls.cs
@@ -10,8 +10,8 @@ public class ReceivedCalls
{
private ICar _car;
const int Rpm = 7000;
- private static readonly object[] Luggage = new[] { new object(), new object() };
- private static readonly DateTime[] ServiceDates = new[] { new DateTime(2001, 01, 01), new DateTime(2002, 02, 02) };
+ private static readonly object[] Luggage = [new object(), new object()];
+ private static readonly DateTime[] ServiceDates = [new DateTime(2001, 01, 01), new DateTime(2002, 02, 02)];
[SetUp]
public void SetUp()
@@ -316,6 +316,16 @@ public void Throw_when_negative_min_range_given()
StringAssert.Contains("minInclusive must be >= 0, but was -1.", ex.Message);
}
+ [Test]
+ public void Works_with_byref_generic_parameters()
+ {
+ IMyService service = Substitute.For();
+ MyArgument arg = new();
+ service.MyMethod(ref arg);
+
+ service.Received().MyMethod(ref Arg.Any());
+ }
+
public interface ICar
{
void Start();
@@ -329,4 +339,11 @@ public interface ICar
float GetCapacityInLitres();
event Action Started;
}
+
+ public interface IMyService
+ {
+ void MyMethod(ref T argument);
+ }
+
+ public class MyArgument { }
}
\ No newline at end of file
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