Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
  • Loading branch information
binodmahto authored Jun 27, 2022
1 parent 1157428 commit 819f28f
Show file tree
Hide file tree
Showing 14 changed files with 311 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@

namespace CoreWebAPIMoqDemo.Services
{
public interface IWeatherForecastService
{
Task<WeatherForecast[]> GetWeatherForecast();
}

public record WeatherForecast(DateTime Date, int TemperatureC, string? Summary)
{
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@

namespace CoreWebAPIMoqDemo.Services
{
public class WeatherForecastService : IWeatherForecastService
{
string[] summaries = new string[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

public async Task<WeatherForecast[]> GetWeatherForecast()
{
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
(
DateTime.Now.AddDays(index),
Random.Shared.Next(-20, 55),
summaries[Random.Shared.Next(summaries.Length)]
)).ToArray();
return forecast;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

<IsPackable>false</IsPackable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="6.0.6" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.1.0" />
<PackageReference Include="Moq" Version="4.18.1" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="3.1.2">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\CoreWebAPIMoqDemo\CoreWebAPIMoqDemo.csproj" />
</ItemGroup>

</Project>
33 changes: 33 additions & 0 deletions CoreWebAPIMoqDemo/CoreWebAPIMoqDemo.Tests/MockServices.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using Moq;
using CoreWebAPIMoqDemo.Services;
using System.Reflection;

namespace CoreWebAPIMoqDemo.Tests
{
internal class MockServices
{
public Mock<IWeatherForecastService> WeatherForecastServiceMock { get; init; }

public MockServices()
{
WeatherForecastServiceMock = new Mock<IWeatherForecastService>();
}

/// <summary>
/// This returns the collection of all mock service's interface type and the mock object, defined here i.e. <see cref="WeatherForecastServiceMock"/>.
/// </summary>
/// <returns></returns>
public IEnumerable<(Type, object)> GetMocks()
{
return GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Select(x =>
{
var interfaceType = x.PropertyType.GetGenericArguments()[0];
var value = x.GetValue(this) as Mock;

return (interfaceType, value.Object);
})
.ToArray();
}
}
}
30 changes: 30 additions & 0 deletions CoreWebAPIMoqDemo/CoreWebAPIMoqDemo.Tests/TestMoqPOCApplication.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using CoreWebAPIMoqDemo.Services;

namespace CoreWebAPIMoqDemo.Tests
{
internal class TestMoqPOCApplication : WebApplicationFactory<Program>
{
private readonly MockServices _mockServices;
public TestMoqPOCApplication(MockServices mockServices)
{
_mockServices = mockServices;
}

protected override IHost CreateHost(IHostBuilder builder)
{
builder.ConfigureServices(services => {
foreach ((var interfaceType, var serviceMock) in _mockServices.GetMocks())
{
services.Remove(services.SingleOrDefault(d => d.ServiceType == interfaceType));
services.AddSingleton(typeof(IWeatherForecastService), serviceMock);
}
});
return base.CreateHost(builder);

}

}
}
1 change: 1 addition & 0 deletions CoreWebAPIMoqDemo/CoreWebAPIMoqDemo.Tests/Usings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
global using Xunit;
38 changes: 38 additions & 0 deletions CoreWebAPIMoqDemo/CoreWebAPIMoqDemo.Tests/WeatherForecastTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
using Moq;
using CoreWebAPIMoqDemo.Services;
using Newtonsoft.Json;

namespace CoreWebAPIMoqDemo.Tests
{
public class WeatherForecastTests
{
private readonly TestMoqPOCApplication _testMoqPOCApplication;
private readonly MockServices _mockServices;
public readonly HttpClient _client;

public WeatherForecastTests()
{
_mockServices = new MockServices();
_testMoqPOCApplication = new TestMoqPOCApplication(_mockServices);
_client = _testMoqPOCApplication.CreateClient();
}

[Fact]
public async void GetWeatherForecastTest()
{
var expResult = new WeatherForecast[]
{
new WeatherForecast(DateTime.Now, 26, "Bengaluru")
};
_mockServices.WeatherForecastServiceMock.Setup(m => m.GetWeatherForecast()).ReturnsAsync(expResult);

var response = await _client.GetAsync("/weatherforecast");
string jsonString = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<WeatherForecast[]>(jsonString);

Assert.Equal(response.StatusCode, System.Net.HttpStatusCode.OK);
Assert.Equal(expResult, result);

}
}
}
17 changes: 17 additions & 0 deletions CoreWebAPIMoqDemo/CoreWebAPIMoqDemo/CoreWebAPIMoqDemo.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\CoreWebAPIMoqDemo.Services\CoreWebAPIMoqDemo.Services.csproj" />
</ItemGroup>

</Project>
32 changes: 32 additions & 0 deletions CoreWebAPIMoqDemo/CoreWebAPIMoqDemo/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using CoreWebAPIMoqDemo.Services;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSingleton<IWeatherForecastService, WeatherForecastService>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();



app.MapGet("/weatherforecast", async (IWeatherForecastService service) =>
{
return await service.GetWeatherForecast();
})
.WithName("GetWeatherForecast");

app.Run();

public partial class Program { }
31 changes: 31 additions & 0 deletions CoreWebAPIMoqDemo/CoreWebAPIMoqDemo/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:56324",
"sslPort": 44384
}
},
"profiles": {
"MoqPOC": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7257;http://localhost:5257",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
9 changes: 9 additions & 0 deletions CoreWebAPIMoqDemo/CoreWebAPIMoqDemo/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
37 changes: 37 additions & 0 deletions CoreWebAPIMoqDemo/MoqDemoSol.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.1.32421.90
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CoreWebAPIMoqDemo", "CoreWebAPIMoqDemo\CoreWebAPIMoqDemo.csproj", "{DC6D47D1-B105-45F2-A6EB-C8748DE5E594}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CoreWebAPIMoqDemo.Services", "CoreWebAPIMoqDemo.Services\CoreWebAPIMoqDemo.Services.csproj", "{5CBB1B82-444D-44D1-8A29-1CB38B47DA69}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CoreWebAPIMoqDemo.Tests", "CoreWebAPIMoqDemo.Tests\CoreWebAPIMoqDemo.Tests.csproj", "{182C832F-5A95-4E6B-A701-D216DF20EE1A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{DC6D47D1-B105-45F2-A6EB-C8748DE5E594}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DC6D47D1-B105-45F2-A6EB-C8748DE5E594}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DC6D47D1-B105-45F2-A6EB-C8748DE5E594}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DC6D47D1-B105-45F2-A6EB-C8748DE5E594}.Release|Any CPU.Build.0 = Release|Any CPU
{5CBB1B82-444D-44D1-8A29-1CB38B47DA69}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5CBB1B82-444D-44D1-8A29-1CB38B47DA69}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5CBB1B82-444D-44D1-8A29-1CB38B47DA69}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5CBB1B82-444D-44D1-8A29-1CB38B47DA69}.Release|Any CPU.Build.0 = Release|Any CPU
{182C832F-5A95-4E6B-A701-D216DF20EE1A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{182C832F-5A95-4E6B-A701-D216DF20EE1A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{182C832F-5A95-4E6B-A701-D216DF20EE1A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{182C832F-5A95-4E6B-A701-D216DF20EE1A}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {8EA605B8-2B7B-4103-95F3-2076EFE612B4}
EndGlobalSection
EndGlobal

0 comments on commit 819f28f

Please sign in to comment.