Skip to content

Replace Moq with NSubstitute #258

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jun 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Yubico.Core/tests/Yubico.Core.UnitTests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,13 @@ limitations under the License. -->
<DefineConstants>Linux</DefineConstants>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="NSubstitute" Version="5.3.0" />
<ProjectReference Include="..\src\Yubico.Core.csproj" />
<PackageReference Include="Xunit.SkippableFact" Version="1.4.13" />
<PackageReference Include="coverlet.collector" Version="6.0.2" PrivateAssets="all" IncludeAssets="runtime; build; native; contentfiles; analyzers; buildtransitive" />
<PackageReference Include="xunit" Version="2.8.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.1" PrivateAssets="all" IncludeAssets="runtime; build; native; contentfiles; analyzers; buildtransitive" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.10.0" />
<PackageReference Include="Moq" Version="4.16.1" />

<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
Expand Down
96 changes: 48 additions & 48 deletions Yubico.Core/tests/Yubico/Core/Devices/Hid/HidConnectionTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,33 +20,33 @@ public class HidConnectionTests
{
private static IHidDDevice GetMockedDevice()
{
var mock = new Mock<IHidDDevice>();
return mock.Object;
var mock = Substitute.For<IHidDDevice>();
return mock;
}

private static byte[] GetFeatureReport() => Hex.HexToBytes("000102030405060708090A0B0C0D0E0F");
private static byte[] GetInputReport() => Hex.HexToBytes("0001020304050607");
private static byte[] GetOutputReport() => Hex.HexToBytes("00010203");

private static Mock<IHidDDevice> GetMockedFeatureDevice()
private static IHidDDevice GetMockedFeatureDevice()
{
var mock = new Mock<IHidDDevice>();
_ = mock.Setup(hdd => hdd.FeatureReportByteLength).Returns(16);
_ = mock.Setup(hdd => hdd.InputReportByteLength).Throws(new Exception());
var mock = Substitute.For<IHidDDevice>();
_ = mock.When(hdd => hdd.FeatureReportByteLength).Returns(16);
_ = mock.InputReportByteLength).Throws(new Exception());
_ = mock.Setup(hdd => hdd.OutputReportByteLength).Throws(new Exception());
_ = mock.Setup(hdd => hdd.GetInputReport()).Throws(new Exception());
_ = mock.Setup(hdd => hdd.GetFeatureReport()).Returns(GetFeatureReport());
_ = mock.Setup(hdd => hdd.GetInputReport()).Throw(new Exception());
_ = mock.When(hdd => hdd.GetFeatureReport().Returns(GetFeatureReport());
return mock;
}

private static Mock<IHidDDevice> GetMockedIODevice()
private static IHidDDevice GetMockedIODevice()
{
var mock = new Mock<IHidDDevice>();
_ = mock.Setup(hdd => hdd.InputReportByteLength).Returns(8);
_ = mock.Setup(hdd => hdd.OutputReportByteLength).Returns(4);
_ = mock.Setup(hdd => hdd.FeatureReportByteLength).Throws(new Exception());
_ = mock.Setup(hdd => hdd.GetFeatureReport()).Throws(new Exception());
_ = mock.Setup(hdd => hdd.GetInputReport()).Returns(GetInputReport());
var mock = Substitute.For<IHidDDevice>();
_ = mock.InputReportByteLength.Returns(8);
_ = mock.OutputReportByteLength.Returns(4);
_ = mock.FeatureReportByteLength).Throws(new Exception());
_ = mock.Setup(hdd => hdd.GetFeatureReport()).Throw(new Exception());
_ = mock.Setup(hdd => hdd.GetInputReport().Returns(GetInputReport());
return mock;
}

Expand All @@ -59,34 +59,34 @@ public void Constructor_GivenDevice_Succeeds()
[Fact]
public void Constructor_GivenFeatureDevice_CallsOpenFeatureConnection()
{
Mock<IHidDDevice> mock = GetMockedFeatureDevice();
using var hc = new HidFeatureReportConnection(mock.Object);
mock.Verify(hdd => hdd.OpenFeatureConnection(), Times.Once());
IHidDDevice mock = GetMockedFeatureDevice();
using var hc = new HidFeatureReportConnection(mock);
mock.Received().OpenFeatureConnection();
}

[Fact]
public void Constructor_GivenFeatureDevice_SetsInputReportSize()
{
Mock<IHidDDevice> mock = GetMockedFeatureDevice();
using var hc = new HidFeatureReportConnection(mock.Object);
IHidDDevice mock = GetMockedFeatureDevice();
using var hc = new HidFeatureReportConnection(mock);

Assert.Equal(hc.InputReportSize, mock.Object.FeatureReportByteLength);
Assert.Equal(hc.InputReportSize, mock.FeatureReportByteLength);
}

[Fact]
public void Constructor_GivenFeatureDevice_SetsOutputReportSize()
{
Mock<IHidDDevice> mock = GetMockedFeatureDevice();
using var hc = new HidFeatureReportConnection(mock.Object);
IHidDDevice mock = GetMockedFeatureDevice();
using var hc = new HidFeatureReportConnection(mock);

Assert.Equal(hc.OutputReportSize, mock.Object.FeatureReportByteLength);
Assert.Equal(hc.OutputReportSize, mock.FeatureReportByteLength);
}

[Fact]
public void SetReport_GivenNullReport_ThrowsArgumentNullException()
{
Mock<IHidDDevice> mock = GetMockedFeatureDevice();
using var hc = new HidFeatureReportConnection(mock.Object);
IHidDDevice mock = GetMockedFeatureDevice();
using var hc = new HidFeatureReportConnection(mock);

#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type.
_ = Assert.Throws<ArgumentNullException>(() => hc.SetReport(null));
Expand All @@ -96,78 +96,78 @@ public void SetReport_GivenNullReport_ThrowsArgumentNullException()
[Fact]
public void SetReport_GivenFeatureReports_CallsSetFeatureReport()
{
Mock<IHidDDevice> mock = GetMockedFeatureDevice();
using var hc = new HidFeatureReportConnection(mock.Object);
IHidDDevice mock = GetMockedFeatureDevice();
using var hc = new HidFeatureReportConnection(mock);

hc.SetReport(GetFeatureReport());

mock.Verify(hdd => hdd.SetFeatureReport(IsSeqEqual(GetFeatureReport())), Times.Once());
mock.Received().SetFeatureReport(IsSeqEqual(GetFeatureReport()));
}

[Fact]
public void GetReport_GivenFeatureReports_CallsGetFeatureReport()
{
Mock<IHidDDevice> mock = GetMockedFeatureDevice();
using var hc = new HidFeatureReportConnection(mock.Object);
IHidDDevice mock = GetMockedFeatureDevice();
using var hc = new HidFeatureReportConnection(mock);

byte[] report = hc.GetReport();

mock.Verify(hdd => hdd.GetFeatureReport(), Times.Once());
mock.Received().GetFeatureReport();
Assert.Equal(GetFeatureReport(), report);
}

[Fact]
public void Constructor_GivenIODevice_CallsOpenIOConnection()
{
Mock<IHidDDevice> mock = GetMockedIODevice();
using var hc = new HidIOReportConnection(mock.Object);
mock.Verify(hdd => hdd.OpenIOConnection(), Times.Once());
IHidDDevice mock = GetMockedIODevice();
using var hc = new HidIOReportConnection(mock);
mock.Received().OpenIOConnection();
}

[Fact]
public void Constructor_GivenIODevice_SetsInputReportSize()
{
Mock<IHidDDevice> mock = GetMockedIODevice();
using var hc = new HidIOReportConnection(mock.Object);
IHidDDevice mock = GetMockedIODevice();
using var hc = new HidIOReportConnection(mock);

Assert.Equal(hc.InputReportSize, mock.Object.InputReportByteLength);
Assert.Equal(hc.InputReportSize, mock.InputReportByteLength);
}

[Fact]
public void Constructor_GivenIODevice_SetsOutputReportSize()
{
Mock<IHidDDevice> mock = GetMockedIODevice();
using var hc = new HidIOReportConnection(mock.Object);
IHidDDevice mock = GetMockedIODevice();
using var hc = new HidIOReportConnection(mock);

Assert.Equal(hc.OutputReportSize, mock.Object.OutputReportByteLength);
Assert.Equal(hc.OutputReportSize, mock.OutputReportByteLength);
}

[Fact]
public void SetReport_GivenIOReports_CallsSetOutputReport()
{
Mock<IHidDDevice> mock = GetMockedIODevice();
using var hc = new HidIOReportConnection(mock.Object);
IHidDDevice mock = GetMockedIODevice();
using var hc = new HidIOReportConnection(mock);

hc.SetReport(GetOutputReport());

mock.Verify(hdd => hdd.SetOutputReport(IsSeqEqual(GetOutputReport())), Times.Once());
mock.Received().SetOutputReport(IsSeqEqual(GetOutputReport()));
}

[Fact]
public void GetReport_GivenIOReports_CallsGetInputReport()
{
Mock<IHidDDevice> mock = GetMockedIODevice();
using var hc = new HidIOReportConnection(mock.Object);
IHidDDevice mock = GetMockedIODevice();
using var hc = new HidIOReportConnection(mock);

byte[] report = hc.GetReport();

mock.Verify(hdd => hdd.GetInputReport(), Times.Once());
mock.Received().GetInputReport();
Assert.Equal(GetInputReport(), report);
}

private static byte[] IsSeqEqual(byte[] val)
{
return It.Is<byte[]>(b => b.SequenceEqual(val));
return Arg.Is<byte[]>(b => b.SequenceEqual(val));
}
}
#endif
Expand Down
14 changes: 7 additions & 7 deletions Yubico.Core/tests/Yubico/Core/Logging/LogTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

using System;
using Microsoft.Extensions.Logging;
using Moq;
using NSubstitute;
using Xunit;

namespace Yubico.Core.Logging
Expand Down Expand Up @@ -49,14 +49,14 @@ public void DefaultLoggerFactory_IsCreated_WhenNoConfigurationProvided()
public void ManualLoggerFactory_SettingInstance_OverridesDefaultFactory()
{
// Arrange
var mockLoggerFactory = new Mock<ILoggerFactory>();
Log.Instance = mockLoggerFactory.Object;
var mockLoggerFactory = Substitute.For<ILoggerFactory>();
Log.Instance = mockLoggerFactory;

// Act
ILoggerFactory actualFactory = Log.Instance;

// Assert
Assert.Same(mockLoggerFactory.Object, actualFactory);
Assert.Same(mockLoggerFactory, actualFactory);
}

// Ensure that LoggerFactory can be replaced manually using the Instance property.
Expand All @@ -65,16 +65,16 @@ public void ManualLoggerFactory_SettingInstance_OverridesDefaultFactory()
public void Legacy_ManualLoggerFactory_SettingInstance_OverridesDefaultFactory()
{
// Arrange
var mockLoggerFactory = new Mock<ILoggerFactory>();
var mockLoggerFactory = Substitute.For<ILoggerFactory>();
#pragma warning disable CS0618 // Type or member is obsolete
Log.LoggerFactory = mockLoggerFactory.Object;
Log.LoggerFactory = mockLoggerFactory;
#pragma warning restore CS0618 // Type or member is obsolete

// Act
ILoggerFactory actualFactory = Log.Instance;

// Assert
Assert.Same(mockLoggerFactory.Object, actualFactory);
Assert.Same(mockLoggerFactory, actualFactory);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ private void InitializeScp11(Scp11KeyParameters keyParameters)
}

[DoesNotReturn]
private T ThrowIfUninitialized<T>() => throw new InvalidOperationException($"{nameof(Scp.ScpState)} has not been initialized. The Setup method must be called.");
private static T ThrowIfUninitialized<T>() => throw new InvalidOperationException($"{nameof(Scp.ScpState)} has not been initialized. The Setup method must be called.");

private static bool ShouldNotEncode(Type commandType)
{
Expand Down
96 changes: 48 additions & 48 deletions Yubico.YubiKey/tests/unit/Yubico.YubiKey.UnitTests.csproj
Original file line number Diff line number Diff line change
@@ -1,48 +1,48 @@
<!-- Copyright 2021 Yubico AB
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<AssemblyName>Yubico.YubiKey.UnitTests</AssemblyName>
<PackageId>Yubico.YubiKey.UnitTests</PackageId>
<RootNamespace></RootNamespace>
<TargetFramework>net8.0</TargetFramework>
<AnalysisMode>AllDisabledByDefault</AnalysisMode>
<!-- StrongName signing -->
<!-- StrongNaming requires that friend assemblies are strong named as well. That means this unit test project must
be strong named, since it uses InternalsVisibleTo. -->
<SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>..\..\..\Yubico.NET.SDK.snk</AssemblyOriginatorKeyFile>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Yubico.YubiKey.csproj" />
<ProjectReference Include="..\utilities\Yubico.YubiKey.TestUtilities.csproj" />
<PackageReference Include="coverlet.collector" Version="6.0.4" PrivateAssets="all" IncludeAssets="runtime; build; native; contentfiles; analyzers; buildtransitive" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.1" PrivateAssets="all" IncludeAssets="runtime; build; native; contentfiles; analyzers; buildtransitive" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="Moq" Version="4.20.72" />
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
<!-- Copyright 2021 Yubico AB

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. -->

<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<AssemblyName>Yubico.YubiKey.UnitTests</AssemblyName>
<PackageId>Yubico.YubiKey.UnitTests</PackageId>
<RootNamespace></RootNamespace>

<TargetFramework>net8.0</TargetFramework>

<AnalysisMode>AllDisabledByDefault</AnalysisMode>

<!-- StrongName signing -->
<!-- StrongNaming requires that friend assemblies are strong named as well. That means this unit test project must
be strong named, since it uses InternalsVisibleTo. -->
<SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>..\..\..\Yubico.NET.SDK.snk</AssemblyOriginatorKeyFile>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\Yubico.YubiKey.csproj" />
<ProjectReference Include="..\utilities\Yubico.YubiKey.TestUtilities.csproj" />
<PackageReference Include="coverlet.collector" Version="6.0.4" PrivateAssets="all" IncludeAssets="runtime; build; native; contentfiles; analyzers; buildtransitive" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.1" PrivateAssets="all" IncludeAssets="runtime; build; native; contentfiles; analyzers; buildtransitive" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="NSubstitute" Version="5.3.0" />
</ItemGroup>

<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
Loading
Loading