Skip to content

Commit

Permalink
Merge pull request #718 from Klantinteractie-Servicesysteem/DIM@6043-…
Browse files Browse the repository at this point in the history
…--Unittests-toevoegen

Dim@6043   unittests toevoegen
  • Loading branch information
JustinICATT authored Sep 21, 2023
2 parents 6694b73 + c6c4c1e commit 4d92a0f
Show file tree
Hide file tree
Showing 15 changed files with 655 additions and 65 deletions.
71 changes: 70 additions & 1 deletion Kiss.Bff.Test/AuthorizationCheckTests.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,19 @@
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Reflection;
using Microsoft.AspNetCore.Mvc.Testing;
using static System.Net.HttpStatusCode;
using Microsoft.AspNetCore.Mvc.Routing;
using System.Net;
using Kiss.Bff.ZaakGerichtWerken.Contactmomenten;
using Kiss.Bff.Beheer.Faq;
using Kiss.Bff.Beheer.Data;
using Microsoft.EntityFrameworkCore;
using Kiss.Bff.Beheer.Gespreksresultaten.Controllers;
using Kiss.Bff.Beheer.Links.Controllers;
using static Kiss.Bff.Beheer.Links.Controllers.LinksController;
using Kiss.Bff.NieuwsEnWerkinstructies.Controllers;
using Kiss.Bff.Beheer.Verwerking;

namespace Kiss.Bff.Test
{
Expand All @@ -23,15 +37,70 @@ public static void ClassCleanup()
s_factory?.Dispose();
}

public static IEnumerable<object[]> GetControllersWithAuthorizeAttributeAndMethods()
{
// Define the controllers and methods to test here
var controllersWithMethodsToTest = new List<(Type controllerType, string methodName, Type[] parameterTypes)>
{
(typeof(ReadContactmomentenDetails), "Get", new Type[0]),
(typeof(GespreksresultatenController), "PutGespreksresultaat", new[] { typeof(Guid), typeof(GespreksresultaatModel), typeof(CancellationToken) }),
(typeof(GespreksresultatenController), "PostGespreksresultaat", new[] { typeof(GespreksresultaatModel), typeof(CancellationToken)}),
(typeof(GespreksresultatenController), "DeleteGespreksresultaat", new[] { typeof(Guid), typeof(CancellationToken)}),
(typeof(LinksController), "PutLink", new[] { typeof(int), typeof(LinkPutModel),typeof(CancellationToken)}),
(typeof(LinksController), "PostLink", new[] { typeof(LinkPostModel) }),
(typeof(LinksController), "DeleteLink", new[] { typeof(int) }),
(typeof(SkillsController), "PutSkill", new[] { typeof(int), typeof(SkillPutModel), typeof(CancellationToken) }),
(typeof(SkillsController), "PostSkill", new[] { typeof(SkillPostModel), typeof(CancellationToken) }),
(typeof(GetVerwerkingsLogs), "Get", new Type[0]),
// Add more controller, method, and parameter combinations as needed
};

foreach (var (controllerType, methodName, parameterTypes) in controllersWithMethodsToTest)
{
yield return new object[] { controllerType, methodName, parameterTypes };
}
}

[DataTestMethod]
[DataRow("/api/postcontactmomenten", "post")]
[DataRow("/api/internetaak/api/version/objects", "post")]
[DataRow("/api/faq")]
[DataRow("/api/contactmomentendetails?id=1")]
public async Task Test(string url, string method = "get")
{
using var request = new HttpRequestMessage(new(method), url);
using var response = await s_client.SendAsync(request);
Assert.AreEqual(Unauthorized, response.StatusCode);
}

[DataTestMethod]
[DynamicData(nameof(GetControllersWithAuthorizeAttributeAndMethods), DynamicDataSourceType.Method)]
public async Task TestAuthorizeAttribute(Type controllerType, string methodName, Type[] parameterTypes)
{
// Manually create an instance of the controller
var dbContextOptions = new DbContextOptionsBuilder<BeheerDbContext>()
.UseInMemoryDatabase(databaseName: "TestDatabase")
.Options;
var dbContext = new BeheerDbContext(dbContextOptions);
var controller = Activator.CreateInstance(controllerType, dbContext) as ControllerBase;

// Assert that the controller instance is not null
Assert.IsNotNull(controller);

// Retrieve the method to test
var method = controllerType.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly, null, parameterTypes, null);

// Assert that the method exists
Assert.IsNotNull(method);

// Retrieve the Authorize attribute
var authorizeAttribute = method.GetCustomAttributes(typeof(AuthorizeAttribute), true)
.FirstOrDefault() as AuthorizeAttribute;

// Assert that the Authorize attribute exists and has the expected policy
Assert.IsNotNull(authorizeAttribute);
Assert.AreEqual(Policies.RedactiePolicy, authorizeAttribute.Policy);
}
}
}

8 changes: 1 addition & 7 deletions Kiss.Bff.Test/CategorienControllerTests.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kiss.Bff.Beheer.Data;
using Kiss.Bff.Beheer.Data;
using Kiss.Bff.Beheer.Links.Controllers;
using Kiss.Bff.Beheer.Links.Data.Entities;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace Kiss.Bff.Test
{
Expand Down
74 changes: 74 additions & 0 deletions Kiss.Bff.Test/GetFaqTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
using Kiss.Bff.Beheer.Data;
using Kiss.Bff.Beheer.Faq;
using Kiss.Bff.ZaakGerichtWerken.Contactmomenten;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

namespace Kiss.Bff.Test
{
[TestClass]
public class GetFaqTests : TestHelper
{
[TestInitialize]
public void Initialize()
{
InitializeDatabase();
}

[TestCleanup]
public void Cleanup()
{
using var dbContext = new BeheerDbContext(_dbContextOptions);
dbContext.Database.EnsureDeleted();
dbContext.Dispose();
}

[TestMethod]
public async Task Get_ReturnsTopQuestions()
{
using var dbContext = new BeheerDbContext(_dbContextOptions);
// Arrange
var controller = new GetFaq(dbContext);

var testData = new List<ContactmomentDetails>();
var topQuestionsCount = 10;

// Add 500 questions
for (int i = 1; i <= 500; i++)
{
testData.Add(new ContactmomentDetails
{
Id = i.ToString(),
Vraag = $"Question {i}",
Einddatum = DateTime.UtcNow
});
}

dbContext.ContactMomentDetails.AddRange(testData);
dbContext.SaveChanges();

// Act
var result = controller.Get() as OkObjectResult;

// Assert
Assert.IsNotNull(result);
Assert.AreEqual(200, result.StatusCode);

var resultList = result.Value as IEnumerable<string>;
Assert.IsNotNull(resultList);

// Ensure that the result contains the top questions
var expectedQuestions = testData
.OrderByDescending(x => x.Einddatum)
.Where(x => !string.IsNullOrWhiteSpace(x.Vraag))
.GroupBy(x => x.Vraag)
.OrderByDescending(x => x.Count())
.Take(topQuestionsCount)
.Select(x => x.Key);

CollectionAssert.AreEqual(expectedQuestions.ToList(), resultList.ToList());
}

}
}
12 changes: 1 addition & 11 deletions Kiss.Bff.Test/GetFeaturedCountControllerTests.cs
Original file line number Diff line number Diff line change
@@ -1,17 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Kiss.Bff.Beheer.Data;
using Kiss.Bff.Beheer.Data;
using Kiss.Bff.NieuwsEnWerkinstructies.Controllers;
using Kiss.Bff.NieuwsEnWerkinstructies.Data.Entities;
using Kiss.Bff.NieuwsEnWerkinstructies.Migrations;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;

namespace Kiss.Bff.Test
{
Expand Down
7 changes: 1 addition & 6 deletions Kiss.Bff.Test/LinksControllerUnitTests.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kiss.Bff.Beheer.Data;
using Kiss.Bff.Beheer.Data;
using Kiss.Bff.Beheer.Links.Controllers;
using Kiss.Bff.Beheer.Links.Data.Entities;
using Microsoft.AspNetCore.Mvc;
Expand Down
10 changes: 1 addition & 9 deletions Kiss.Bff.Test/MarkeerGelezenControllerTests.cs
Original file line number Diff line number Diff line change
@@ -1,17 +1,9 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using IdentityModel;
using System.Security.Claims;
using Kiss.Bff.Beheer.Data;
using Kiss.Bff.NieuwsEnWerkinstructies.Controllers;
using Kiss.Bff.NieuwsEnWerkinstructies.Data.Entities;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;

namespace Kiss.Bff.Test
{
Expand Down
104 changes: 104 additions & 0 deletions Kiss.Bff.Test/ReadContactmomentenDetailsTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
using System;
using System.Linq.Expressions;
using System.Security.Claims;
using Kiss.Bff.Beheer.Data;
using Kiss.Bff.ZaakGerichtWerken.Contactmomenten;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

namespace Kiss.Bff.Test
{
[TestClass]
public class ReadContactmomentenDetailsTests : TestHelper
{
private IServiceProvider? _serviceProvider;

[TestInitialize]
public void Initialize()
{
InitializeDatabase();
SeedTestData();

var services = new ServiceCollection();
var user = new ClaimsPrincipal(new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.NameIdentifier, "testuser"),
new Claim(ClaimTypes.Role, Policies.RedactiePolicy)
}));
services.AddSingleton<IHttpContextAccessor>(_ => new HttpContextAccessor { HttpContext = new DefaultHttpContext { User = user } });
_serviceProvider = services.BuildServiceProvider();
}

[TestCleanup]
public void Cleanup()
{
using var dbContext = new BeheerDbContext(_dbContextOptions);
dbContext.Database.EnsureDeleted();
dbContext.Dispose();
}

private void SeedTestData()
{
using var dbContext = new BeheerDbContext(_dbContextOptions);
var contactmoment1 = new ContactmomentDetails
{
Id = "1",
Startdatum = DateTime.Now,
Einddatum = DateTime.Now.AddHours(1),
Gespreksresultaat = "Result 1",
Vraag = "Question 1"
};

var contactmoment2 = new ContactmomentDetails
{
Id = "2",
Startdatum = DateTime.Now,
Einddatum = DateTime.Now.AddHours(1),
Gespreksresultaat = "Result 2",
Vraag = "Question 2"
};

dbContext.ContactMomentDetails.AddRange(contactmoment1, contactmoment2);
dbContext.SaveChanges();
}

[TestMethod]
public async Task Get_ValidId_ReturnsOk()
{
using var dbContext = new BeheerDbContext(_dbContextOptions);
// Arrange
var controller = new ReadContactmomentenDetails(dbContext);
var validId = "1";

// Act
var result = await controller.Get(validId, CancellationToken.None) as OkObjectResult;

// Assert
Assert.IsNotNull(result);
Assert.AreEqual(200, result.StatusCode);

var contactmoment = result.Value as ContactmomentDetails;
Assert.IsNotNull(contactmoment);
Assert.AreEqual(validId, contactmoment.Id);
}

[TestMethod]
public async Task Get_InvalidId_ReturnsNotFound()
{
using var dbContext = new BeheerDbContext(_dbContextOptions);
// Arrange
var controller = new ReadContactmomentenDetails(dbContext);
var invalidId = "nonexistent";

// Act
var result = await controller.Get(invalidId, CancellationToken.None) as NotFoundResult;

// Assert
Assert.IsNotNull(result);
Assert.AreEqual(404, result.StatusCode);
}
}
}
Loading

0 comments on commit 4d92a0f

Please sign in to comment.