using System; using System.Threading; using System.Threading.Tasks; using MongoDB.Driver; using Moq; using Retroactiune.Core.Entities; using Retroactiune.Core.Interfaces; using Retroactiune.Core.Services; using Xunit; namespace Retroactiune.Tests.Retroactiune.Core.Services { public class TestTokensService { [Fact] public async Task Test_GenerateTokensAsync_InvalidNumberOfTokens() { // Setup var mongoDatabaseMock = new Mock(); var mongoClientMock = new Mock(); var mongoSettingsMock = new Mock(); var mongoCollectionMock = new Mock>(); mongoSettingsMock.SetupGet(i => i.DatabaseName).Returns("MyDB"); mongoSettingsMock.SetupGet(i => i.TokensCollectionName).Returns("tokens"); mongoClientMock .Setup(stub => stub.GetDatabase(It.IsAny(), It.IsAny())) .Returns(mongoDatabaseMock.Object); mongoDatabaseMock .Setup(i => i.GetCollection(It.IsAny(), It.IsAny())) .Returns(mongoCollectionMock.Object); // Test & Assert var service = new TokenService(mongoClientMock.Object, mongoSettingsMock.Object); await Assert.ThrowsAsync(async () => { await service.GenerateTokensAsync(-1, ""); }); } [Fact] public async Task Test_GenerateTokensAsync_Success() { // Setup var mongoDatabaseMock = new Mock(); var mongoClientMock = new Mock(); var mongoSettingsMock = new Mock(); var mongoCollectionMock = new Mock>(); mongoSettingsMock.SetupGet(i => i.DatabaseName).Returns("MyDB"); mongoSettingsMock.SetupGet(i => i.TokensCollectionName).Returns("tokens"); mongoClientMock .Setup(stub => stub.GetDatabase(It.IsAny(), It.IsAny())) .Returns(mongoDatabaseMock.Object); mongoDatabaseMock .Setup(i => i.GetCollection(It.IsAny(), It.IsAny())) .Returns(mongoCollectionMock.Object); // Test var expiryTime = DateTime.UtcNow; var service = new TokenService(mongoClientMock.Object, mongoSettingsMock.Object); await service.GenerateTokensAsync(3, "Hello", expiryTime); // Assert var item = new Token { Id = null, ExpiryTime = expiryTime, TimeUsed = null, FeedbackReceiverId = "Hello", CreatedAt = expiryTime }; mongoCollectionMock.Verify( i => i.InsertManyAsync(new[] {item, item, item}, It.IsAny(), It.IsAny()), Times.Once); } [Fact] public async Task Test_DeleteTokens_Ok() { // Setup var mongoDatabaseMock = new Mock(); var mongoClientMock = new Mock(); var mongoSettingsMock = new Mock(); var mongoCollectionMock = new Mock>(); mongoSettingsMock.SetupGet(i => i.DatabaseName).Returns("MyDB"); mongoSettingsMock.SetupGet(i => i.TokensCollectionName).Returns("tokens"); mongoClientMock .Setup(stub => stub.GetDatabase(It.IsAny(), It.IsAny())) .Returns(mongoDatabaseMock.Object); mongoDatabaseMock .Setup(i => i.GetCollection(It.IsAny(), It.IsAny())) .Returns(mongoCollectionMock.Object); // Test var service = new TokenService(mongoClientMock.Object, mongoSettingsMock.Object); await service.DeleteTokens(new[] {"test_id"}); // Assert mongoCollectionMock.Verify( i => i.DeleteManyAsync( It.IsAny>(), It.IsAny()), Times.Once); } } }