🧪 Add somes console and unit tests
continuous-integration/drone/push Build is failing
Details
continuous-integration/drone/push Build is failing
Details
parent
7cfe9981e2
commit
d4176ee17b
@ -0,0 +1,112 @@
|
||||
using Xunit;
|
||||
using Model2Entities;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using DbContextLib;
|
||||
using StubbedContextLib;
|
||||
using System.Linq;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using System;
|
||||
using Shared;
|
||||
using Model;
|
||||
using Moq;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Entities;
|
||||
|
||||
namespace UnitTestsEntities
|
||||
{
|
||||
public class ActivityRepositoryTests : IClassFixture<DatabaseFixture>
|
||||
{
|
||||
private readonly DatabaseFixture _fixture;
|
||||
|
||||
public ActivityRepositoryTests(DatabaseFixture fixture)
|
||||
{
|
||||
_fixture = fixture;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetActivities_ReturnsActivities()
|
||||
{
|
||||
var options = new DbContextOptionsBuilder<HeartTrackContext>()
|
||||
.UseSqlite(_fixture._connection)
|
||||
.Options;
|
||||
|
||||
using (var context = new HeartTrackContext(options))
|
||||
{
|
||||
context.Database.EnsureCreated();
|
||||
}
|
||||
|
||||
using (var context = new HeartTrackContext(options))
|
||||
{
|
||||
var repository = new DbDataManager.ActivityRepository(new DbDataManager(context), null);
|
||||
var activities = await repository.GetActivities(0, 10, ActivityOrderCriteria.None);
|
||||
|
||||
Assert.NotNull(activities);
|
||||
Assert.Equal(10, activities.Count());
|
||||
}
|
||||
}
|
||||
[Fact]
|
||||
public async Task GetActivityByIdAsync_ReturnsCorrectActivity_WhenIdExists()
|
||||
{
|
||||
// Arrange
|
||||
var activityId = 1;
|
||||
var expectedActivity = new Activity { Id = activityId, Type = "Running" };
|
||||
|
||||
var mockDataManager = new Mock<DbDataManager>();
|
||||
mockDataManager.Setup(dm => dm.DbContext.ActivitiesSet.SingleOrDefaultAsync(a => a.IdActivity == activityId))
|
||||
.ReturnsAsync(expectedActivity.ToEntity());
|
||||
|
||||
var loggerMock = new Mock<ILogger<DbDataManager>>();
|
||||
var activityRepository = new DbDataManager.ActivityRepository(mockDataManager.Object, loggerMock.Object);
|
||||
|
||||
// Act
|
||||
var result = await activityRepository.GetActivityByIdAsync(activityId);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(expectedActivity.Id, result.Id);
|
||||
Assert.Equal(expectedActivity.Type, result.Type);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetActivityByIdAsync_ReturnsNull_WhenIdDoesNotExist()
|
||||
{
|
||||
// Arrange
|
||||
var activityId = 999;
|
||||
|
||||
var mockDataManager = new Mock<DbDataManager>();
|
||||
mockDataManager.Setup(dm => dm.DbContext.ActivitiesSet.SingleOrDefaultAsync(a => a.IdActivity == activityId))
|
||||
.ReturnsAsync((ActivityEntity)null);
|
||||
|
||||
var loggerMock = new Mock<ILogger<DbDataManager>>();
|
||||
var activityRepository = new DbDataManager.ActivityRepository(mockDataManager.Object, loggerMock.Object);
|
||||
|
||||
// Act
|
||||
var result = await activityRepository.GetActivityByIdAsync(activityId);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddActivity_SuccessfullyAddsNewActivity()
|
||||
{
|
||||
// Arrange
|
||||
var newActivity = new Activity { Type = "Walking" };
|
||||
|
||||
var mockDataManager = new Mock<DbDataManager>();
|
||||
mockDataManager.Setup(dm => dm.DbContext.AddItem(It.IsAny<ActivityEntity>()))
|
||||
.ReturnsAsync(newActivity.ToEntity());
|
||||
|
||||
var loggerMock = new Mock<ILogger<DbDataManager>>();
|
||||
var activityRepository = new DbDataManager.ActivityRepository(mockDataManager.Object, loggerMock.Object);
|
||||
|
||||
// Act
|
||||
var result = await activityRepository.AddActivity(newActivity);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(newActivity.Type, result.Type);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1 @@
|
||||
global using Xunit;
|
@ -0,0 +1,31 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.0" />
|
||||
<PackageReference Include="Moq" Version="4.20.70" />
|
||||
<PackageReference Include="xunit" Version="2.4.2" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.0">
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
</PackageReference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\Model2Entities\Model2Entities.csproj" />
|
||||
<ProjectReference Include="..\UnitTestsEntities\UnitTestsEntities.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
@ -0,0 +1,10 @@
|
||||
namespace RepositoriesUnitTest;
|
||||
|
||||
public class UnitTest1
|
||||
{
|
||||
[Fact]
|
||||
public void Test1()
|
||||
{
|
||||
|
||||
}
|
||||
}
|
@ -1 +0,0 @@
|
||||
global using Microsoft.VisualStudio.TestTools.UnitTesting;
|
@ -1,26 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.0"/>
|
||||
<PackageReference Include="MSTest.TestAdapter" Version="3.0.4"/>
|
||||
<PackageReference Include="MSTest.TestFramework" Version="3.0.4"/>
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.0"/>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\HeartTrackAPI\HeartTrackAPI.csproj" />
|
||||
<ProjectReference Include="..\..\Model\Model.csproj" />
|
||||
<ProjectReference Include="..\..\Shared\Shared.csproj" />
|
||||
<ProjectReference Include="..\..\StubAPI\StubAPI.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
@ -0,0 +1,110 @@
|
||||
/*!
|
||||
* \file BookDataServiceAPI.cs
|
||||
* \author HeartTeam
|
||||
* \brief Fichier contenant la classe BookDataServiceAPI.
|
||||
*/
|
||||
|
||||
using System.Diagnostics;
|
||||
using Dto;
|
||||
using Model.Repository;
|
||||
using Shared;
|
||||
using APIMappers;
|
||||
|
||||
/*!
|
||||
* \brief Implémentation de l'interface IActivityRepository pour récupérer des activités via un service HTTP.
|
||||
*/
|
||||
public class ActivityServiceAPI : IActivityRepository
|
||||
{
|
||||
private HttpRequest<ActivityDto> myRequest = new HttpRequest<ActivityDto>();
|
||||
|
||||
/*!
|
||||
* \brief Constructeur de la classe ActivityServiceAPI.
|
||||
* Initialise l'adresse de base du client HTTP.
|
||||
*/
|
||||
public ActivityServiceAPI()
|
||||
{
|
||||
myRequest.HttpClient.BaseAddress = new Uri("http://localhost:5030/api/v1/Activity/");
|
||||
}
|
||||
|
||||
/*!
|
||||
* \brief Récupère toutes les Activités de manière asynchrone.
|
||||
* \return Une tâche représentant l'opération asynchrone qui retourne une liste d'Activity.
|
||||
*/
|
||||
public async Task<IEnumerable<Model.Activity>?> GetActivities(int index, int count, ActivityOrderCriteria criteria, bool descending = false)
|
||||
{
|
||||
var activityDtos = await myRequest.GetAllAsync();
|
||||
return activityDtos?.ToModels();
|
||||
}
|
||||
|
||||
/*!
|
||||
* \brief Récupère les activités par index et compte de manière asynchrone.
|
||||
* \param index L'index de départ pour la pagination.
|
||||
* \param count Le nombre d'éléments à récupérer.
|
||||
* \return Une tâche représentant l'opération asynchrone qui retourne une liste d'Activity.
|
||||
*/
|
||||
public async Task<List<Model.Activity>> GetBooksAsync(ActivityOrderCriteria criteria, bool descending, int index, int count)
|
||||
{
|
||||
var activityDtos = await myRequest.GetAsync(criteria, descending, index, count);
|
||||
return (List<Model.Activity>)activityDtos.ToModels();
|
||||
}
|
||||
|
||||
/*!
|
||||
* \brief Récupère une activité par son identifiant de manière asynchrone.
|
||||
* \param id L'identifiant du livre à récupérer.
|
||||
* \return Une tâche représentant l'opération asynchrone qui retourne une liste d'Activity.
|
||||
*/
|
||||
public async Task<IEnumerable<Model.Activity>?> GetActivityByIdAsync(int id)
|
||||
{
|
||||
var activityDtos = await myRequest.GetByIdAsync(id);
|
||||
return activityDtos.ToModels();
|
||||
}
|
||||
|
||||
/*!
|
||||
* \brief Ajoute une activité de manière asynchrone.
|
||||
* \param activity L'Activity à ajouter.
|
||||
* \return Une tâche représentant l'opération asynchrone qui retourne l'activité ajouté (Activity).
|
||||
*/
|
||||
public async Task<Model.Activity?> AddActivity(Model.Activity activity)
|
||||
{
|
||||
return await myRequest.PostAsync(activity.ToDto()).ToModel();
|
||||
}
|
||||
|
||||
/*!
|
||||
* \brief Met à jour une activité de manière asynchrone.
|
||||
* \param id L'identifiant de l'activité à mettre à jour.
|
||||
* \param activity Les nouvelles données de l'activité à mettre à jour.
|
||||
* \return Une tâche représentant l'opération asynchrone qui retourne l'activité mis à jour (Activity).
|
||||
*/
|
||||
public async Task<Model.Activity?> UpdateActivity(int id, Model.Activity activity)
|
||||
{
|
||||
var activityDto = activity.ToDto();
|
||||
var updatedActivityDto = await myRequest.PutAsync(id, activityDto);
|
||||
return updatedActivityDto?.ToModel();
|
||||
}
|
||||
|
||||
/*!
|
||||
* \brief Supprime une activité de manière asynchrone.
|
||||
* \param id L'identifiant de l'activité à supprimer.
|
||||
* \return Une tâche représentant l'opération asynchrone.
|
||||
*/
|
||||
public async Task<bool> DeleteActivity(int id)
|
||||
{
|
||||
await myRequest.DeleteAsync(id);
|
||||
return true;
|
||||
}
|
||||
|
||||
public Task<int> GetNbItems()
|
||||
{
|
||||
return myRequest.GetNbItems();
|
||||
}
|
||||
|
||||
public Task<IEnumerable<Model.Activity>?> GetActivitiesByUser(int userId, int index, int count, ActivityOrderCriteria orderCriteria, bool descending = false)
|
||||
{
|
||||
return (List<ActivityDto>)myRequest.GetActivitiesByUser(userId, index, count, orderCriteria, descending).ToModels();
|
||||
}
|
||||
|
||||
public Task<int> GetNbActivitiesByUser(int userId)
|
||||
{
|
||||
return myRequest.GetNbActivitiesByUser(userId);
|
||||
}
|
||||
}
|
@ -0,0 +1,99 @@
|
||||
/*!
|
||||
* \file HttpRequest.cs
|
||||
* \author Antoine PEREDERII
|
||||
* \brief Fichier contenant la classe HttpRequest.
|
||||
*/
|
||||
|
||||
using System.Diagnostics;
|
||||
using System.Net.Http.Json;
|
||||
using Dto;
|
||||
using Shared;
|
||||
|
||||
/*!
|
||||
* \brief Classe représentant un client HTTP pour les requêtes vers un service de gestion de livres.
|
||||
*/
|
||||
public class HttpRequest<T> where T : class
|
||||
{
|
||||
private HttpClient _httpClient { get; } = new HttpClient();
|
||||
public HttpClient HttpClient => _httpClient;
|
||||
|
||||
/*!
|
||||
* \brief Récupère tous les livres de manière asynchrone.
|
||||
* \return Une tâche représentant l'opération asynchrone qui retourne une liste de T.
|
||||
*/
|
||||
public async Task<List<T>> GetAllAsync()
|
||||
{
|
||||
return await _httpClient.GetFromJsonAsync<List<T>>("");
|
||||
}
|
||||
|
||||
/*!
|
||||
* \brief Récupère les activités par index et compte de manière asynchrone.
|
||||
* \param index L'index de départ pour la pagination.
|
||||
* \param count Le nombre d'éléments à récupérer.
|
||||
* \return Une tâche représentant l'opération asynchrone qui retourne une liste de T.
|
||||
*/
|
||||
public async Task<List<T>> GetAsync((ActivityOrderCriteria, AthleteOrderCriteria) criteria, bool descending, int index, int count)
|
||||
{
|
||||
return await _httpClient.GetFromJsonAsync<List<T>>($"?OrderingPropertyName={criteria}&Descending={descending}&Index={index}&Count={count}");
|
||||
}
|
||||
|
||||
/*!
|
||||
* \brief Récupère un livre par son identifiant de manière asynchrone.
|
||||
* \param id L'identifiant du livre à récupérer.
|
||||
* \return Une tâche représentant l'opération asynchrone qui retourne une liste de T.
|
||||
*/
|
||||
public async Task<List<T>> GetByIdAsync(int id)
|
||||
{
|
||||
return await _httpClient.GetFromJsonAsync<List<T>>($"{id}");
|
||||
}
|
||||
|
||||
public Task<int> GetNbItems()
|
||||
{
|
||||
return _httpClient.GetFromJsonAsync<int>("count");
|
||||
}
|
||||
|
||||
public Task<IEnumerable<T>?> GetActivitiesByUser(int userId, int index, int count, (ActivityOrderCriteria, AthleteOrderCriteria) orderCriteria, bool descending = false)
|
||||
{
|
||||
return _httpClient.GetFromJsonAsync<IEnumerable<T>?>($"?userId={userId}&index={index}&count={count}&orderCriteria={orderCriteria}&descending={descending}");
|
||||
}
|
||||
|
||||
public Task<int> GetNbActivitiesByUser(int userId)
|
||||
{
|
||||
return _httpClient.GetFromJsonAsync<int>($"count?userId={userId}");
|
||||
}
|
||||
|
||||
/*!
|
||||
* \brief Ajoute un livre de manière asynchrone.
|
||||
* \param book Le livre à ajouter.
|
||||
* \return Une tâche représentant l'opération asynchrone qui retourne le livre ajouté (T).
|
||||
*/
|
||||
public async Task<T> PostAsync(T activity)
|
||||
{
|
||||
var response = await _httpClient.PostAsJsonAsync("", activity);
|
||||
|
||||
return await response.Content.ReadFromJsonAsync<T>();
|
||||
}
|
||||
|
||||
/*!
|
||||
* \brief Met à jour un livre de manière asynchrone.
|
||||
* \param id L'identifiant du livre à mettre à jour.
|
||||
* \param book Les nouvelles données du livre à mettre à jour.
|
||||
* \return Une tâche représentant l'opération asynchrone qui retourne le livre mis à jour (T).
|
||||
*/
|
||||
public async Task<T> PutAsync(int id, T activity)
|
||||
{
|
||||
var response = await _httpClient.PutAsJsonAsync($"{id}", activity);
|
||||
|
||||
return await response.Content.ReadFromJsonAsync<T>();
|
||||
}
|
||||
|
||||
/*!
|
||||
* \brief Supprime un livre de manière asynchrone.
|
||||
* \param id L'identifiant du livre à supprimer.
|
||||
* \return Une tâche représentant l'opération asynchrone.
|
||||
*/
|
||||
public async Task DeleteAsync(int id)
|
||||
{
|
||||
await _httpClient.DeleteAsync($"{id}");
|
||||
}
|
||||
}
|
Loading…
Reference in new issue