Skip to content

Commit

Permalink
Merge pull request #20 from sliedig/unmock
Browse files Browse the repository at this point in the history
feat: replaced moq with NSubsitute
  • Loading branch information
sliedig authored Aug 14, 2023
2 parents c2430ff + f479752 commit d12a087
Show file tree
Hide file tree
Showing 16 changed files with 153 additions and 167 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@
<PackageReference Include="Amazon.Lambda.Core" Version="2.1.0" />
<PackageReference Include="Amazon.Lambda.DynamoDBEvents" Version="2.1.1" />
<PackageReference Include="Amazon.Lambda.TestUtilities" Version="2.0.0" />
<PackageReference Include="AWSSDK.DynamoDBv2" Version="3.7.200.9" />
<PackageReference Include="AWSSDK.DynamoDBv2" Version="3.7.200.17" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.7.0" />
<PackageReference Include="Moq" Version="4.18.4" />
<PackageReference Include="NSubstitute" Version="5.0.0" />
<PackageReference Include="xunit" Version="2.5.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@
using System.Threading.Tasks;
using Amazon.DynamoDBv2.DataModel;
using Amazon.Lambda.APIGatewayEvents;
using Moq;
using NSubstitute;
using Xunit;
using Xunit.Abstractions;

[assembly: CollectionBehavior(DisableTestParallelization = true)]

namespace Unicorn.Contracts.ContractService.Tests;

[Collection("Sequential")]
Expand All @@ -31,10 +33,10 @@ public async Task CreateValidContractPublishesDraftContractStatusChangedEvent()
{
// Arrange
var request = TestHelpers.LoadApiGatewayProxyRequest("./events/create_valid_event.json");

var mockDynamoDbContext = new Mock<IDynamoDBContext>();

var mockPublisher = new Mock<IPublisher>();
var mockDynamoDbContext = Substitute.For<IDynamoDBContext>();

var mockPublisher = Substitute.For<IPublisher>();

var context = TestHelpers.NewLambdaContext();

Expand All @@ -45,13 +47,12 @@ public async Task CreateValidContractPublishesDraftContractStatusChangedEvent()
};

var function =
new CreateContractFunction(mockDynamoDbContext.Object, mockPublisher.Object);
new CreateContractFunction(mockDynamoDbContext, mockPublisher);

var response = await function.FunctionHandler(request, context);

mockPublisher.Verify(
client => client.PublishEvent(It.IsAny<Contract>()), Times.Once); //TODO: Verify with contract status = DRAFT


await mockPublisher.Received(1).PublishEvent(Arg.Any<Contract>());

_testOutputHelper.WriteLine("Lambda Response: \n" + response.Body);
_testOutputHelper.WriteLine("Expected Response: \n" + expectedResponse.Body);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Amazon.DynamoDBv2.DataModel;
using Amazon.Lambda.APIGatewayEvents;
using Moq;
using NSubstitute;
using Xunit;
using Xunit.Abstractions;

Expand All @@ -22,7 +23,7 @@ public class UpdateContractFunctionTest
public UpdateContractFunctionTest(ITestOutputHelper testOutputHelper)
{
_testOutputHelper = testOutputHelper;
// Set env variable for Powertools Metrics
Environment.SetEnvironmentVariable("POWERTOOLS_METRICS_NAMESPACE", "ContractService");
}
Expand All @@ -31,40 +32,36 @@ public UpdateContractFunctionTest(ITestOutputHelper testOutputHelper)
public async Task UpdateContractPublishesApprovedContractStatusChangedEvent()
{
var request = TestHelpers.LoadApiGatewayProxyRequest("./events/update_valid_event.json");

var mockDynamoDbContext = new Mock<IDynamoDBContext>();
var retContract = new Contract()
{
PropertyId = "usa/anytown/main-street/123",
ContractId = Guid.NewGuid(),
Address = new Address()

var mockDynamoDbContext = Substitute.For<IDynamoDBContext>();

mockDynamoDbContext.LoadAsync<Contract>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(new Contract()
{
City = "anytown",
Number = 123,
Street = "main-street"
}
};

mockDynamoDbContext
.Setup(x => x.LoadAsync<Contract>(It.IsAny<string>(), CancellationToken.None).Result)
.Returns(retContract);
var mockPublisher = new Mock<IPublisher>();
PropertyId = "usa/anytown/main-street/123",
ContractId = Guid.NewGuid(),
Address = new Address()
{
City = "anytown",
Number = 123,
Street = "main-street"
}
});

var mockPublisher = Substitute.For<IPublisher>();

var context = TestHelpers.NewLambdaContext();
var context = TestHelpers.NewLambdaContext();

var expectedResponse = new APIGatewayProxyResponse
{
StatusCode = (int)HttpStatusCode.OK,
Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } }
};

var function = new UpdateContractFunction(mockDynamoDbContext.Object, mockPublisher.Object);
var function = new UpdateContractFunction(mockDynamoDbContext, mockPublisher);
var response = await function.FunctionHandler(request, context);

mockPublisher.Verify(
client => client.PublishEvent(It.IsAny<Contract>()), Times.Once);
//TODO: Verify with contract status = DRAFT
await mockPublisher.Received(1).PublishEvent(Arg.Any<Contract>());

_testOutputHelper.WriteLine("Lambda Response: \n" + response.Body);
_testOutputHelper.WriteLine("Expected Response: \n" + expectedResponse.Body);
Expand Down
4 changes: 2 additions & 2 deletions Unicorn.Contracts/ContractsService/ContractsService.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@
<PackageReference Include="AWS.Lambda.Powertools.Logging" Version="1.1.1" />
<PackageReference Include="AWS.Lambda.Powertools.Metrics" Version="1.3.2" />
<PackageReference Include="AWS.Lambda.Powertools.Tracing" Version="1.1.1" />
<PackageReference Include="AWSSDK.DynamoDBv2" Version="3.7.200.9" />
<PackageReference Include="AWSSDK.EventBridge" Version="3.7.200.10" />
<PackageReference Include="AWSSDK.DynamoDBv2" Version="3.7.200.17" />
<PackageReference Include="AWSSDK.EventBridge" Version="3.7.200.16" />
<PackageReference Include="AWSXRayRecorder.Handlers.AwsSdk" Version="2.12.0" />
</ItemGroup>
</Project>
Expand Down
4 changes: 2 additions & 2 deletions Unicorn.Contracts/ContractsService/UpdateContractFunction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,9 @@ public UpdateContractFunction(IDynamoDBContext dynamoDbContext, IPublisher publi
/// <param name="apigProxyEvent">API Gateway Lambda Proxy Request that triggers the function.</param>
/// <param name="context">The context for the Lambda function.</param>
/// <returns>API Gateway Lambda Proxy Response.</returns>
[Tracing]
[Logging(LogEvent = true)]
[Metrics(CaptureColdStart = true)]
[Logging(LogEvent = true, CorrelationIdPath = CorrelationIdPaths.ApiGatewayRest)]
[Tracing(CaptureMode = TracingCaptureMode.ResponseAndError)]
public async Task<APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyRequest apigProxyEvent,
ILambdaContext context)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
using Amazon.DynamoDBv2.DataModel;
using Amazon.StepFunctions;
using Amazon.StepFunctions.Model;
using Moq;
using NSubstitute;
using Xunit;
using Xunit.Abstractions;

Expand Down Expand Up @@ -39,33 +39,31 @@ public void StatusIsDraftSyncShouldNotSendTaskSuccess()
// Setup
var ddbEvent = TestHelpers.LoadDynamoDbEventSource("./events/StreamEvents/contract_status_changed_draft.json");

var retContractStatusItem = new ContractStatusItem
{
PropertyId = "usa/anytown/main-street/999",
ContractId = Guid.NewGuid(),
ContractStatus = "DRAFT",
ContractLastModifiedOn = DateTime.Today,
SfnWaitApprovedTaskToken = null
};

var mockDynamoDbContext = new Mock<IDynamoDBContext>();

mockDynamoDbContext
.Setup(x => x.LoadAsync<ContractStatusItem>(It.IsAny<string>(), CancellationToken.None).Result)
.Returns(retContractStatusItem);

var mockStepFunctionsClient = new Mock<AmazonStepFunctionsClient>();

var mockDynamoDbContext = Substitute.For<IDynamoDBContext>();

mockDynamoDbContext.LoadAsync<ContractStatusItem>(Arg.Any<string>(), Arg.Is(CancellationToken.None))
.Returns(new ContractStatusItem
{
PropertyId = "usa/anytown/main-street/999",
ContractId = Guid.NewGuid(),
ContractStatus = "DRAFT",
ContractLastModifiedOn = DateTime.Today,
SfnWaitApprovedTaskToken = null
});

var mockStepFunctionsClient = Substitute.ForPartsOf<AmazonStepFunctionsClient>();
mockStepFunctionsClient.Received(0)
.SendTaskSuccessAsync(Arg.Any<SendTaskSuccessRequest>(),
Arg.Any<CancellationToken>());
var context = TestHelpers.NewLambdaContext();

var function =
new PropertiesApprovalSyncFunction(mockStepFunctionsClient.Object, mockDynamoDbContext.Object);
new PropertiesApprovalSyncFunction(mockStepFunctionsClient, mockDynamoDbContext);

var handler = function.FunctionHandler(ddbEvent, context);

function.FunctionHandler(ddbEvent, context);

mockStepFunctionsClient.Verify(
client => client.SendTaskSuccessAsync(It.IsAny<SendTaskSuccessRequest>(),
It.IsAny<CancellationToken>()), Times.Never);
}


Expand All @@ -75,32 +73,32 @@ public Task StatusIsApprovedNoTokenSyncShouldNotSendTaskSuccess()
var ddbEvent =
TestHelpers.LoadDynamoDbEventSource("./events/StreamEvents/contract_status_changed_approved.json");

var retContractStatusItem = new ContractStatusItem
{
PropertyId = "usa/anytown/main-street/999",
ContractId = Guid.NewGuid(),
ContractStatus = "APPROVED",
ContractLastModifiedOn = DateTime.Today,
SfnWaitApprovedTaskToken = null
};

var mockDynamoDbContext = new Mock<IDynamoDBContext>();
mockDynamoDbContext
.Setup(x => x.LoadAsync<ContractStatusItem>(It.IsAny<string>(), CancellationToken.None).Result)
.Returns(retContractStatusItem);

var mockStepFunctionsClient = new Mock<AmazonStepFunctionsClient>();

var mockDynamoDbContext = Substitute.For<IDynamoDBContext>();
mockDynamoDbContext.LoadAsync<ContractStatusItem>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(new ContractStatusItem
{
PropertyId = "usa/anytown/main-street/999",
ContractId = Guid.NewGuid(),
ContractStatus = "APPROVED",
ContractLastModifiedOn = DateTime.Today,
SfnWaitApprovedTaskToken = null
});

var mockStepFunctionsClient = Substitute.ForPartsOf<AmazonStepFunctionsClient>();
mockStepFunctionsClient.Received(0).
SendTaskSuccessAsync(Arg.Any<SendTaskSuccessRequest>(),
Arg.Any<CancellationToken>());
var context = TestHelpers.NewLambdaContext();

var function =
new PropertiesApprovalSyncFunction(mockStepFunctionsClient.Object, mockDynamoDbContext.Object);
new PropertiesApprovalSyncFunction(mockStepFunctionsClient, mockDynamoDbContext);

function.FunctionHandler(ddbEvent, context);

mockStepFunctionsClient.Verify(
client => client.SendTaskSuccessAsync(It.IsAny<SendTaskSuccessRequest>(),
It.IsAny<CancellationToken>()), Times.Never);
mockStepFunctionsClient.Received(0).
SendTaskSuccessAsync(Arg.Any<SendTaskSuccessRequest>(),
Arg.Any<CancellationToken>());

return Task.CompletedTask;
}
Expand All @@ -113,32 +111,30 @@ public Task StatusIsDraftWithTokenSyncShouldNotSendTaskSuccess()
TestHelpers.LoadDynamoDbEventSource(
"./events/StreamEvents/contract_status_draft_waiting_for_approval.json");

var retContractStatusItem = new ContractStatusItem
{
PropertyId = "usa/anytown/main-street/999",
ContractId = Guid.NewGuid(),
ContractStatus = "DRAFT",
ContractLastModifiedOn = DateTime.Today,
SfnWaitApprovedTaskToken = Token
};

var mockDynamoDbContext = new Mock<IDynamoDBContext>();
mockDynamoDbContext
.Setup(x => x.LoadAsync<ContractStatusItem>(It.IsAny<string>(), CancellationToken.None).Result)
.Returns(retContractStatusItem);
var mockDynamoDbContext = Substitute.For<IDynamoDBContext>();

mockDynamoDbContext.LoadAsync<ContractStatusItem>(Arg.Any<string>(), CancellationToken.None)
.Returns(new ContractStatusItem
{
PropertyId = "usa/anytown/main-street/999",
ContractId = Guid.NewGuid(),
ContractStatus = "DRAFT",
ContractLastModifiedOn = DateTime.Today,
SfnWaitApprovedTaskToken = Token
});

var mockStepFunctionsClient = new Mock<AmazonStepFunctionsClient>();
var mockStepFunctionsClient = Substitute.ForPartsOf<AmazonStepFunctionsClient>();

var context = TestHelpers.NewLambdaContext();

var function =
new PropertiesApprovalSyncFunction(mockStepFunctionsClient.Object, mockDynamoDbContext.Object);
new PropertiesApprovalSyncFunction(mockStepFunctionsClient, mockDynamoDbContext);

var handler = function.FunctionHandler(ddbEvent, context);

mockStepFunctionsClient.Verify(
client => client.SendTaskSuccessAsync(It.IsAny<SendTaskSuccessRequest>(),
It.IsAny<CancellationToken>()), Times.Never);
mockStepFunctionsClient.Received(0).
SendTaskSuccessAsync(Arg.Any<SendTaskSuccessRequest>(),
Arg.Any<CancellationToken>());

return Task.CompletedTask;
}
Expand All @@ -151,31 +147,27 @@ public Task StatusIsApprovedWithTokenSyncShouldSendTaskSuccess()
TestHelpers.LoadDynamoDbEventSource(
"./events/StreamEvents/contract_status_changed_approved_waiting_for_approval.json");

var retContractStatusItem = new ContractStatusItem
{
PropertyId = "usa/anytown/main-street/999",
ContractId = Guid.NewGuid(),
ContractStatus = "APPROVED",
ContractLastModifiedOn = DateTime.Today,
SfnWaitApprovedTaskToken = Token
};

var mockStepFunctionsClient = new Mock<AmazonStepFunctionsClient>();
var mockDynamoDbContext = new Mock<IDynamoDBContext>();
mockDynamoDbContext
.Setup(x =>
x.LoadAsync<ContractStatusItem>(It.IsAny<string>(),
CancellationToken.None).Result)
.Returns(retContractStatusItem);
var mockStepFunctionsClient = Substitute.ForPartsOf<AmazonStepFunctionsClient>();
var mockDynamoDbContext = Substitute.For<IDynamoDBContext>();

mockDynamoDbContext.LoadAsync<ContractStatusItem>(Arg.Any<string>(), Arg.Is(CancellationToken.None))
.Returns(new ContractStatusItem
{
PropertyId = "usa/anytown/main-street/999",
ContractId = Guid.NewGuid(),
ContractStatus = "APPROVED",
ContractLastModifiedOn = DateTime.Today,
SfnWaitApprovedTaskToken = Token
});
var context = TestHelpers.NewLambdaContext();

var function =
new PropertiesApprovalSyncFunction(mockStepFunctionsClient.Object, mockDynamoDbContext.Object);
new PropertiesApprovalSyncFunction(mockStepFunctionsClient, mockDynamoDbContext);
var handler = function.FunctionHandler(ddbEvent, context);

mockStepFunctionsClient.Verify(
client => client.SendTaskSuccessAsync(It.IsAny<SendTaskSuccessRequest>(),
It.IsAny<CancellationToken>()), Times.Once);
mockStepFunctionsClient.Received(1).
SendTaskSuccessAsync(Arg.Any<SendTaskSuccessRequest>(),
Arg.Any<CancellationToken>());

return Task.CompletedTask;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,13 @@
<PackageReference Include="Amazon.Lambda.Core" Version="2.1.0" />
<PackageReference Include="Amazon.Lambda.TestUtilities" Version="2.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.7.0" />
<PackageReference Include="Moq" Version="4.18.4" />
<PackageReference Include="NSubstitute" Version="5.0.0" />
<PackageReference Include="NSubstitute.Analyzers.CSharp" Version="1.0.16">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="xunit" Version="2.5.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
Expand Down
Loading

0 comments on commit d12a087

Please sign in to comment.