Вроде усе

This commit is contained in:
2025-06-07 17:57:26 +04:00
parent f91a3cfca8
commit 50491ec87b
16 changed files with 707 additions and 34 deletions

View File

@@ -0,0 +1,107 @@
using ClassLibrary1;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace BussinessLogick;
internal class ArticalBussinessLogick(IArticleStorageContract articleStorageContract, ILogger logger) : IArticleBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IArticleStorageContract _articleStorageContract = articleStorageContract;
public List<Article> GetAllArticles()
{
_logger.LogInformation("Get all articles");
var articles = _articleStorageContract.GetList() ?? throw new NullListException();
return articles;
}
public Article GetArticleByData(string data)
{
_logger.LogInformation("Get article by data: {data}", data);
if (data.IsEmpty())
throw new ArgumentException(nameof(data));
if (data.IsGuid())
{
var article = _articleStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
return article;
}
else
{
var article = _articleStorageContract.GetElementByTitle(data) ?? throw new ElementNotFoundException(data);
return article;
}
}
public void InsertArticle(Article article)
{
_logger.LogInformation("Insert article: {json}", JsonSerializer.Serialize(article));
ArgumentNullException.ThrowIfNull(article);
article.Validate();
var existingById = _articleStorageContract.GetElementById(article.Id);
if (existingById != null)
throw new ElementNotFoundException($"Article with Id {article.Id} already exists");
var existingByTitle = _articleStorageContract.GetElementByTitle(article.Title);
if (existingByTitle != null)
throw new ElementNotFoundException($"Article with Title {article.Title} already exists");
try
{
_articleStorageContract.AddElement(article);
}
catch (Exception ex)
{
throw new ElementNotFoundException("Error adding article to storage");
}
}
public void UpdateArticle(Article article)
{
_logger.LogInformation("Update article: {json}", JsonSerializer.Serialize(article));
ArgumentNullException.ThrowIfNull(article);
article.Validate();
var existing = _articleStorageContract.GetElementById(article.Id) ?? throw new ElementNotFoundException(article.Id);
var existingByTitle = _articleStorageContract.GetElementByTitle(article.Title);
if (existingByTitle != null && existingByTitle.Id != article.Id)
throw new ElementNotFoundException($"Article with Title {article.Title} already exists");
try
{
_articleStorageContract.UpdElement(article);
}
catch (Exception ex)
{
throw new ElementNotFoundException("Error updating article in storage");
}
}
public void DeleteArticle(string id)
{
_logger.LogInformation("Delete article by id: {id}", id);
if (id.IsEmpty())
throw new ArgumentException(nameof(id));
if (!id.IsGuid())
throw new ValidationException("Id is not a unique identifier");
var existing = _articleStorageContract.GetElementById(id) ?? throw new ElementNotFoundException(id);
try
{
_articleStorageContract.DelElement(id);
}
catch (Exception ex)
{
throw new ElementNotFoundException("Error deleting article from storage");
}
}
}

View File

@@ -0,0 +1,113 @@
using ClassLibrary1;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace BussinessLogick;
internal class AuthorBusinessLogic(IAuthorStorageContract authorStorageContract, ILogger logger) : IAuthorBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IAuthorStorageContract _authorStorageContract = authorStorageContract;
public List<Author> GetAllAuthors()
{
_logger.LogInformation("Get all authors");
var authors = _authorStorageContract.GetList() ?? throw new NullListException();
return authors;
}
public Author GetAuthorByData(string data)
{
_logger.LogInformation("Get author by data: {data}", data);
if (data.IsEmpty())
throw new ArgumentException(nameof(data));
if (data.IsGuid())
{
var author = _authorStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
return author;
}
else if (Regex.IsMatch(data, @"^([a-zA-Z0-9._%-]+)@([a-zA-Z0-9.-]+)\.([a-zA-Z]{2,})$"))
{
var author = _authorStorageContract.GetElementByEmail(data) ?? throw new ElementNotFoundException(data);
return author;
}
else
{
var author = _authorStorageContract.GetElementByFIO(data) ?? throw new ElementNotFoundException(data);
return author;
}
}
public void InsertAuthor(Author author)
{
_logger.LogInformation("Insert author: {json}", JsonSerializer.Serialize(author));
ArgumentNullException.ThrowIfNull(author);
author.Validate();
var existingById = _authorStorageContract.GetElementById(author.Id);
if (existingById != null)
throw new ElementNotFoundException($"Author with Id {author.Id} already exists");
var existingByEmail = _authorStorageContract.GetElementByEmail(author.Email);
if (existingByEmail != null)
throw new ElementNotFoundException($"Author with Email {author.Email} already exists");
try
{
_authorStorageContract.AddElement(author);
}
catch (Exception ex)
{
throw new ElementNotFoundException("Error adding author to storage");
}
}
public void UpdateAuthor(Author author)
{
_logger.LogInformation("Update author: {json}", JsonSerializer.Serialize(author));
ArgumentNullException.ThrowIfNull(author);
author.Validate();
var existing = _authorStorageContract.GetElementById(author.Id) ?? throw new ElementNotFoundException(author.Id);
var existingByEmail = _authorStorageContract.GetElementByEmail(author.Email);
if (existingByEmail != null && existingByEmail.Id != author.Id)
throw new ElementNotFoundException($"Author with Email {author.Email} already exists");
try
{
_authorStorageContract.UpdElement(author);
}
catch (Exception ex)
{
throw new ElementNotFoundException("Error updating author in storage");
}
}
public void DeleteAuthor(string id)
{
_logger.LogInformation("Delete author by id: {id}", id);
if (id.IsEmpty())
throw new ArgumentException(nameof(id));
if (!id.IsGuid())
throw new ValidationException("Id is not a unique identifier");
var existing = _authorStorageContract.GetElementById(id) ?? throw new ElementNotFoundException(id);
try
{
_authorStorageContract.DelElement(id);
}
catch (Exception ex)
{
throw new ElementNotFoundException("Error deleting author from storage");
}
}
}

View File

@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="Test" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.5" />
<PackageReference Include="System.Text.Json" Version="9.0.5" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ClassLibrary1\ClassLibrary1.csproj" />
</ItemGroup>
</Project>

View File

@@ -7,6 +7,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ClassLibrary1", "ClassLibra
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Test", "Test\Test.csproj", "{8FC911A3-5BFF-4FFC-A8EE-B38E44B572FB}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Test", "Test\Test.csproj", "{8FC911A3-5BFF-4FFC-A8EE-B38E44B572FB}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BussinessLogick", "BussinessLogick\BussinessLogick.csproj", "{D098214E-146D-4B68-9EF7-89F5DB610CB7}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
@@ -21,6 +23,10 @@ Global
{8FC911A3-5BFF-4FFC-A8EE-B38E44B572FB}.Debug|Any CPU.Build.0 = Debug|Any CPU {8FC911A3-5BFF-4FFC-A8EE-B38E44B572FB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8FC911A3-5BFF-4FFC-A8EE-B38E44B572FB}.Release|Any CPU.ActiveCfg = Release|Any CPU {8FC911A3-5BFF-4FFC-A8EE-B38E44B572FB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8FC911A3-5BFF-4FFC-A8EE-B38E44B572FB}.Release|Any CPU.Build.0 = Release|Any CPU {8FC911A3-5BFF-4FFC-A8EE-B38E44B572FB}.Release|Any CPU.Build.0 = Release|Any CPU
{D098214E-146D-4B68-9EF7-89F5DB610CB7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D098214E-146D-4B68-9EF7-89F5DB610CB7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D098214E-146D-4B68-9EF7-89F5DB610CB7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D098214E-146D-4B68-9EF7-89F5DB610CB7}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE

View File

@@ -20,12 +20,9 @@ namespace ClassLibrary1
throw new ValidationException("Id is Guid"); throw new ValidationException("Id is Guid");
if (Title.IsEmpty()) if (Title.IsEmpty())
throw new ValidationException("Field Id is empty"); throw new ValidationException("Field Id is empty");
if (!Title.IsGuid())
throw new ValidationException("Id is Guid");
if (Tema.IsEmpty()) if (Tema.IsEmpty())
throw new ValidationException("Field Id is empty"); throw new ValidationException("Field Id is empty");
if (!Tema.IsGuid())
throw new ValidationException("Id is Guid");
} }
} }
} }

View File

@@ -24,16 +24,12 @@ namespace ClassLibrary1
throw new ValidationException("The value in the field Id is not a unique identifier"); throw new ValidationException("The value in the field Id is not a unique identifier");
if (FIO.IsEmpty()) if (FIO.IsEmpty())
throw new ValidationException("Field FIO is empty"); throw new ValidationException("Field FIO is empty");
if (!FIO.IsGuid())
throw new ValidationException("Field FIO is guid");
if (ArticleId.IsEmpty()) if (ArticleId.IsEmpty())
throw new ValidationException("Field ArticleId is empty"); throw new ValidationException("Field ArticleId is empty");
if (!ArticleId.IsGuid()) if (!ArticleId.IsGuid())
throw new ValidationException("The value in the field ArticleId is not a unique identifier"); throw new ValidationException("The value in the field ArticleId is not a unique identifier");
if (Work.IsEmpty()) if (Work.IsEmpty())
throw new ValidationException("Field ArticleId is empty"); throw new ValidationException("Field ArticleId is empty");
if (!Work.IsGuid())
throw new ValidationException("The value in the field ArticleId is not a unique identifier");
if (BirthDate.Date > DateTime.Now.AddYears(-16).Date) if (BirthDate.Date > DateTime.Now.AddYears(-16).Date)
throw new ValidationException($"Minors cannot be hired (BirthDate = {BirthDate.ToShortDateString()})"); throw new ValidationException($"Minors cannot be hired (BirthDate = {BirthDate.ToShortDateString()})");
if (Email.IsEmpty()) if (Email.IsEmpty())

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibrary1;
public class ElementNotFoundException : Exception
{
public string Value { get; private set; }
public ElementNotFoundException(string value) : base($"Element not found at value = {value}")
{
Value = value;
}
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibrary1;
public interface IArticleBusinessLogicContract
{
List<Article> GetAllArticles();
Article GetArticleByData(string data);
void InsertArticle(Article article);
void UpdateArticle(Article article);
void DeleteArticle(string id);
}

View File

@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibrary1;
public interface IArticleStorageContract
{
List<Article> GetList();
Article? GetElementById(string id);
Article? GetElementByTitle(string title);
void AddElement(Article article);
void UpdElement(Article article);
void DelElement(string id);
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibrary1;
public interface IAuthorBusinessLogicContract
{
List<Author> GetAllAuthors();
Author GetAuthorByData(string data);
void InsertAuthor(Author author);
void UpdateAuthor(Author author);
void DeleteAuthor(string id);
}

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibrary1;
public interface IAuthorStorageContract
{
List<Author> GetList();
Author? GetElementById(string id);
Author? GetElementByFIO(string fio);
Author? GetElementByEmail(string email);
void AddElement(Author author);
void UpdElement(Author author);
void DelElement(string id);
}

View File

@@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibrary1;
public class NullListException : Exception
{
public NullListException() : base("The returned list is null") { }
}

View File

@@ -38,12 +38,7 @@ internal class ArticleTests
Assert.That(() => article.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => article.Validate(), Throws.TypeOf<ValidationException>());
} }
[Test]
public void TitleIsNotGuidTest()
{
var article = CreateArticle(Guid.NewGuid().ToString(), "not-a-guid", Guid.NewGuid().ToString(), DateTime.UtcNow.AddDays(-1));
Assert.That(() => article.Validate(), Throws.TypeOf<ValidationException>());
}
[Test] [Test]
public void TemaIsNullOrEmptyTest() public void TemaIsNullOrEmptyTest()
@@ -55,12 +50,7 @@ internal class ArticleTests
Assert.That(() => article.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => article.Validate(), Throws.TypeOf<ValidationException>());
} }
[Test]
public void TemaIsNotGuidTest()
{
var article = CreateArticle(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "not-a-guid", DateTime.UtcNow.AddDays(-1));
Assert.That(() => article.Validate(), Throws.TypeOf<ValidationException>());
}
@@ -68,8 +58,8 @@ internal class ArticleTests
public void AllFieldsAreCorrectTest() public void AllFieldsAreCorrectTest()
{ {
var id = Guid.NewGuid().ToString(); var id = Guid.NewGuid().ToString();
var title = Guid.NewGuid().ToString(); // Title должен быть GUID согласно текущей валидации var title = Guid.NewGuid().ToString();
var tema = Guid.NewGuid().ToString(); // Tema должен быть GUID согласно текущей валидации var tema = Guid.NewGuid().ToString();
var dateCreat = DateTime.UtcNow.AddDays(-1); var dateCreat = DateTime.UtcNow.AddDays(-1);
var article = CreateArticle(id, title, tema, dateCreat); var article = CreateArticle(id, title, tema, dateCreat);

355
Test/AuthorBussinessTest.cs Normal file
View File

@@ -0,0 +1,355 @@
using ClassLibrary1;
using Moq;
using BussinessLogick;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace Test;
[TestFixture]
internal class AuthorBussinessTest
{
private AuthorBusinessLogic _authorBusinessLogic;
private Mock<IAuthorStorageContract> _authorStorageContract;
private Mock<ILogger> _loggerMock;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_authorStorageContract = new Mock<IAuthorStorageContract>();
_loggerMock = new Mock<ILogger>();
_authorBusinessLogic = new AuthorBusinessLogic(_authorStorageContract.Object, _loggerMock.Object);
}
[SetUp]
public void SetUp()
{
_authorStorageContract.Reset();
}
// Тесты для GetAllAuthors
[Test]
public void GetAllAuthors_ReturnListOfRecords_Test()
{
// Arrange
var authorsList = new List<Author>
{
new Author(Guid.NewGuid().ToString(), "Author 1", "author1@example.com", DateTime.Now.AddYears(-30), Guid.NewGuid().ToString(), Guid.NewGuid().ToString()),
new Author(Guid.NewGuid().ToString(), "Author 2", "author2@example.com", DateTime.Now.AddYears(-25), Guid.NewGuid().ToString(), Guid.NewGuid().ToString())
};
_authorStorageContract.Setup(x => x.GetList()).Returns(authorsList);
// Act
var result = _authorBusinessLogic.GetAllAuthors();
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result, Is.EquivalentTo(authorsList));
_authorStorageContract.Verify(x => x.GetList(), Times.Once());
}
[Test]
public void GetAllAuthors_ReturnEmptyList_Test()
{
// Arrange
_authorStorageContract.Setup(x => x.GetList()).Returns(new List<Author>());
// Act
var result = _authorBusinessLogic.GetAllAuthors();
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result, Is.Empty);
_authorStorageContract.Verify(x => x.GetList(), Times.Once());
}
[Test]
public void GetAllAuthors_ReturnNull_ThrowException_Test()
{
// Arrange
_authorStorageContract.Setup(x => x.GetList()).Returns((List<Author>)null);
// Act & Assert
Assert.Throws<NullListException>(() => _authorBusinessLogic.GetAllAuthors());
_authorStorageContract.Verify(x => x.GetList(), Times.Once());
}
// Тесты для GetAuthorByData
[Test]
public void GetAuthorByData_GetById_ReturnRecord_Test()
{
// Arrange
var id = Guid.NewGuid().ToString();
var author = new Author(id, "Author 1", "author1@example.com", DateTime.Now.AddYears(-30), Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
_authorStorageContract.Setup(x => x.GetElementById(id)).Returns(author);
// Act
var result = _authorBusinessLogic.GetAuthorByData(id);
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result.Id, Is.EqualTo(id));
_authorStorageContract.Verify(x => x.GetElementById(id), Times.Once());
}
[Test]
public void GetAuthorByData_GetByEmail_ReturnRecord_Test()
{
// Arrange
var email = "author1@example.com";
var author = new Author(Guid.NewGuid().ToString(), "Author 1", email, DateTime.Now.AddYears(-30), Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
_authorStorageContract.Setup(x => x.GetElementByEmail(email)).Returns(author);
// Act
var result = _authorBusinessLogic.GetAuthorByData(email);
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result.Email, Is.EqualTo(email));
_authorStorageContract.Verify(x => x.GetElementByEmail(email), Times.Once());
}
[Test]
public void GetAuthorByData_GetByFIO_ReturnRecord_Test()
{
// Arrange
var fio = "Author 1";
var author = new Author(Guid.NewGuid().ToString(), fio, "author1@example.com", DateTime.Now.AddYears(-30), Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
_authorStorageContract.Setup(x => x.GetElementByFIO(fio)).Returns(author);
// Act
var result = _authorBusinessLogic.GetAuthorByData(fio);
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result.FIO, Is.EqualTo(fio));
_authorStorageContract.Verify(x => x.GetElementByFIO(fio), Times.Once());
}
[Test]
public void GetAuthorByData_EmptyData_ThrowException_Test()
{
// Act & Assert
Assert.Throws<ArgumentException>(() => _authorBusinessLogic.GetAuthorByData(null));
Assert.Throws<ArgumentException>(() => _authorBusinessLogic.GetAuthorByData(string.Empty));
_authorStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never());
_authorStorageContract.Verify(x => x.GetElementByEmail(It.IsAny<string>()), Times.Never());
_authorStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Never());
}
[Test]
public void GetAuthorByData_GetById_NotFound_ThrowException_Test()
{
// Arrange
var id = Guid.NewGuid().ToString();
_authorStorageContract.Setup(x => x.GetElementById(id)).Returns((Author)null);
// Act & Assert
Assert.Throws<ElementNotFoundException>(() => _authorBusinessLogic.GetAuthorByData(id));
_authorStorageContract.Verify(x => x.GetElementById(id), Times.Once());
}
[Test]
public void GetAuthorByData_GetByEmail_NotFound_ThrowException_Test()
{
// Arrange
var email = "author1@example.com";
_authorStorageContract.Setup(x => x.GetElementByEmail(email)).Returns((Author)null);
// Act & Assert
Assert.Throws<ElementNotFoundException>(() => _authorBusinessLogic.GetAuthorByData(email));
_authorStorageContract.Verify(x => x.GetElementByEmail(email), Times.Once());
}
[Test]
public void GetAuthorByData_GetByFIO_NotFound_ThrowException_Test()
{
// Arrange
var fio = "Author 1";
_authorStorageContract.Setup(x => x.GetElementByFIO(fio)).Returns((Author)null);
// Act & Assert
Assert.Throws<ElementNotFoundException>(() => _authorBusinessLogic.GetAuthorByData(fio));
_authorStorageContract.Verify(x => x.GetElementByFIO(fio), Times.Once());
}
// Тесты для InsertAuthor
[Test]
public void InsertAuthor_ValidAuthor_Success_Test()
{
// Arrange
var author = new Author(Guid.NewGuid().ToString(), "Author 1", "author1@example.com", DateTime.Now.AddYears(-30), Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
_authorStorageContract.Setup(x => x.GetElementById(author.Id)).Returns((Author)null);
_authorStorageContract.Setup(x => x.GetElementByEmail(author.Email)).Returns((Author)null);
// Act
_authorBusinessLogic.InsertAuthor(author);
// Assert
_authorStorageContract.Verify(x => x.AddElement(author), Times.Once());
}
[Test]
public void InsertAuthor_DuplicateId_ThrowException_Test()
{
// Arrange
var author = new Author(Guid.NewGuid().ToString(), "Author 1", "author1@example.com", DateTime.Now.AddYears(-30), Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
_authorStorageContract.Setup(x => x.GetElementById(author.Id)).Returns(author);
// Act & Assert
Assert.Throws<ElementNotFoundException>(() => _authorBusinessLogic.InsertAuthor(author));
_authorStorageContract.Verify(x => x.AddElement(It.IsAny<Author>()), Times.Never());
}
[Test]
public void InsertAuthor_DuplicateEmail_ThrowException_Test()
{
// Arrange
var author = new Author(Guid.NewGuid().ToString(), "Author 1", "author1@example.com", DateTime.Now.AddYears(-30), Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
_authorStorageContract.Setup(x => x.GetElementById(author.Id)).Returns((Author)null);
_authorStorageContract.Setup(x => x.GetElementByEmail(author.Email)).Returns(author);
// Act & Assert
Assert.Throws<ElementNotFoundException>(() => _authorBusinessLogic.InsertAuthor(author));
_authorStorageContract.Verify(x => x.AddElement(It.IsAny<Author>()), Times.Never());
}
[Test]
public void InsertAuthor_NullAuthor_ThrowException_Test()
{
// Act & Assert
Assert.Throws<ArgumentNullException>(() => _authorBusinessLogic.InsertAuthor(null));
_authorStorageContract.Verify(x => x.AddElement(It.IsAny<Author>()), Times.Never());
}
[Test]
public void InsertAuthor_InvalidAuthor_ThrowException_Test()
{
// Arrange
var author = new Author("", "Author 1", "invalid_email", DateTime.Now.AddYears(-10), "", "");
// Act & Assert
Assert.Throws<ValidationException>(() => _authorBusinessLogic.InsertAuthor(author));
_authorStorageContract.Verify(x => x.AddElement(It.IsAny<Author>()), Times.Never());
}
// Тесты для UpdateAuthor
[Test]
public void UpdateAuthor_ValidAuthor_Success_Test()
{
// Arrange
var author = new Author(Guid.NewGuid().ToString(), "Author 1", "author1@example.com", DateTime.Now.AddYears(-30), Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
_authorStorageContract.Setup(x => x.GetElementById(author.Id)).Returns(author);
_authorStorageContract.Setup(x => x.GetElementByEmail(author.Email)).Returns((Author)null);
// Act
_authorBusinessLogic.UpdateAuthor(author);
// Assert
_authorStorageContract.Verify(x => x.UpdElement(author), Times.Once());
}
[Test]
public void UpdateAuthor_NonExistingAuthor_ThrowException_Test()
{
// Arrange
var author = new Author(Guid.NewGuid().ToString(), "Author 1", "author1@example.com", DateTime.Now.AddYears(-30), Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
_authorStorageContract.Setup(x => x.GetElementById(author.Id)).Returns((Author)null);
// Act & Assert
Assert.Throws<ElementNotFoundException>(() => _authorBusinessLogic.UpdateAuthor(author));
_authorStorageContract.Verify(x => x.UpdElement(It.IsAny<Author>()), Times.Never());
}
[Test]
public void UpdateAuthor_DuplicateEmail_ThrowException_Test()
{
// Arrange
var author = new Author(Guid.NewGuid().ToString(), "Author 1", "author1@example.com", DateTime.Now.AddYears(-30), Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
var existingAuthor = new Author(Guid.NewGuid().ToString(), "Author 2", "author1@example.com", DateTime.Now.AddYears(-25), Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
_authorStorageContract.Setup(x => x.GetElementById(author.Id)).Returns(author);
_authorStorageContract.Setup(x => x.GetElementByEmail(author.Email)).Returns(existingAuthor);
// Act & Assert
Assert.Throws<ElementNotFoundException>(() => _authorBusinessLogic.UpdateAuthor(author));
_authorStorageContract.Verify(x => x.UpdElement(It.IsAny<Author>()), Times.Never());
}
[Test]
public void UpdateAuthor_NullAuthor_ThrowException_Test()
{
// Act & Assert
Assert.Throws<ArgumentNullException>(() => _authorBusinessLogic.UpdateAuthor(null));
_authorStorageContract.Verify(x => x.UpdElement(It.IsAny<Author>()), Times.Never());
}
[Test]
public void UpdateAuthor_InvalidAuthor_ThrowException_Test()
{
// Arrange
var author = new Author("", "Author 1", "invalid_email", DateTime.Now.AddYears(-10), "", "");
// Act & Assert
Assert.Throws<ValidationException>(() => _authorBusinessLogic.UpdateAuthor(author));
_authorStorageContract.Verify(x => x.UpdElement(It.IsAny<Author>()), Times.Never());
}
// Тесты для DeleteAuthor
[Test]
public void DeleteAuthor_ValidId_Success_Test()
{
// Arrange
var id = Guid.NewGuid().ToString();
var author = new Author(id, "Author 1", "author1@example.com", DateTime.Now.AddYears(-30), Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
_authorStorageContract.Setup(x => x.GetElementById(id)).Returns(author);
// Act
_authorBusinessLogic.DeleteAuthor(id);
// Assert
_authorStorageContract.Verify(x => x.DelElement(id), Times.Once());
}
[Test]
public void DeleteAuthor_NonExistingId_ThrowException_Test()
{
// Arrange
var id = Guid.NewGuid().ToString();
_authorStorageContract.Setup(x => x.GetElementById(id)).Returns((Author)null);
// Act & Assert
Assert.Throws<ElementNotFoundException>(() => _authorBusinessLogic.DeleteAuthor(id));
_authorStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never());
}
[Test]
public void DeleteAuthor_EmptyId_ThrowException_Test()
{
// Act & Assert
Assert.Throws<ArgumentException>(() => _authorBusinessLogic.DeleteAuthor(null));
Assert.Throws<ArgumentException>(() => _authorBusinessLogic.DeleteAuthor(string.Empty));
_authorStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never());
}
[Test]
public void DeleteAuthor_InvalidId_ThrowException_Test()
{
// Arrange
var invalidId = "not-a-guid";
// Act & Assert
Assert.Throws<ValidationException>(() => _authorBusinessLogic.DeleteAuthor(invalidId));
_authorStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never());
}
}

View File

@@ -37,12 +37,7 @@ internal class AuthorTests
Assert.That(() => author.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => author.Validate(), Throws.TypeOf<ValidationException>());
} }
[Test]
public void FIOIsNotGuidTest()
{
var author = CreateAuthor(Guid.NewGuid().ToString(), "not-a-guid", "test@example.com", DateTime.UtcNow.AddYears(-20), Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
Assert.That(() => author.Validate(), Throws.TypeOf<ValidationException>());
}
[Test] [Test]
public void ArticleIdIsNullOrEmptyTest() public void ArticleIdIsNullOrEmptyTest()
@@ -71,12 +66,7 @@ internal class AuthorTests
Assert.That(() => author.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => author.Validate(), Throws.TypeOf<ValidationException>());
} }
[Test]
public void WorkIsNotGuidTest()
{
var author = CreateAuthor(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "test@example.com", DateTime.UtcNow.AddYears(-20), "not-a-guid", Guid.NewGuid().ToString());
Assert.That(() => author.Validate(), Throws.TypeOf<ValidationException>());
}
[Test] [Test]
public void EmailIsNullOrEmptyTest() public void EmailIsNullOrEmptyTest()

View File

@@ -11,6 +11,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.2" /> <PackageReference Include="coverlet.collector" Version="6.0.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageReference Include="Moq" Version="4.20.72" />
<PackageReference Include="NUnit" Version="4.2.2" /> <PackageReference Include="NUnit" Version="4.2.2" />
<PackageReference Include="NUnit.Analyzers" Version="4.4.0" /> <PackageReference Include="NUnit.Analyzers" Version="4.4.0" />
<PackageReference Include="NUnit3TestAdapter" Version="4.6.0" /> <PackageReference Include="NUnit3TestAdapter" Version="4.6.0" />
@@ -18,6 +19,7 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\ClassLibrary1\ClassLibrary1.csproj" /> <ProjectReference Include="..\ClassLibrary1\ClassLibrary1.csproj" />
<ProjectReference Include="..\BussinessLogick\BussinessLogick.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>