Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add tests #3

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions BookStoreAPI.Tests/BookStoreAPI.Tests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<Project Sdk="Microsoft.NET.Sdk">

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

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

<ItemGroup>
<PackageReference Include="AngleSharp" Version="0.17.1"/>
<PackageReference Include="AutoMapper" Version="12.0.1"/>
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="7.0.0"/>
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="7.0.0"/>
<PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="7.0.0"/>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="7.0.0"/>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.10"/>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="7.0.10"/>
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.10">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>

<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.4.0"/>
<PackageReference Include="xunit" Version="2.4.2"/>
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>

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

<ItemGroup>
<Content Update="xunit.runner.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>
46 changes: 46 additions & 0 deletions BookStoreAPI.Tests/BookStoreWebApplicationFactory.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
using System.Data.Common;
using BookStoreAPI.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

namespace BookStoreAPI.Tests;

public class BookStoreWebApplicationFactory<TProgram> : WebApplicationFactory<TProgram> where TProgram : class
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureServices(services =>
{
var dbContextDescriptor =
services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions<BookStoreDatabaseContext>));

services.Remove(dbContextDescriptor);

var dbConnectionDescriptor = services.SingleOrDefault(
d => d.ServiceType == typeof(DbConnection));

services.Remove(dbConnectionDescriptor);

services.AddSingleton<DbConnection>(container =>
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();

return connection;
});

services.AddDbContext<BookStoreDatabaseContext>((container, options) =>
{
var connection = container.GetRequiredService<DbConnection>();
options.UseSqlite(connection);
});

services.AddAutoMapper(typeof(Program));
});

builder.UseEnvironment("Development");
}
}
233 changes: 233 additions & 0 deletions BookStoreAPI.Tests/IntegrationTests/Books/BooksTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,233 @@
using System.Net;
using System.Text;
using AutoMapper;
using BookStoreAPI.Functions.Commands.Book.Create;
using BookStoreAPI.Functions.Commands.Book.Patch;
using BookStoreAPI.Models;
using BookStoreAPI.Tests.Utils;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Xunit;

namespace BookStoreAPI.Tests.IntegrationTests.Books;

public class BooksTests : IClassFixture<BookStoreWebApplicationFactory<Program>>
{
private readonly BookStoreWebApplicationFactory<Program> _factory;
private readonly IMapper _mapper;
private readonly IServiceProvider _serviceProvider;

public BooksTests(BookStoreWebApplicationFactory<Program> factory)
{
_factory = factory;

_serviceProvider = _factory.Services;
_mapper = _serviceProvider.GetRequiredService<IMapper>();

Data.SeedData(_serviceProvider);
}

[Fact]
public async Task Get_ReturnsListOfAllBooksFromDatabase()
{
using var scope = _factory.Services.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<BookStoreDatabaseContext>();

var client = _factory.CreateClient();

var response = await client.GetAsync("/api/BookStore");
response.EnsureSuccessStatusCode();
var contentString = await response.Content.ReadAsStringAsync();
var books = JsonConvert.DeserializeObject<List<BookDto>>(contentString);

var currentBooks = await dbContext.Books.Include(b => b.RentalHistory).Include(b => b.Genre).ToListAsync();
var currentBooksDto = _mapper.Map<List<BookDto>>(currentBooks);

Assert.NotNull(books);
Assert.NotEmpty(books);
Assert.Equivalent(currentBooksDto, books);
}

[Fact]
public async Task Get_ReturnsBookFromDatabase()
{
using var scope = _factory.Services.CreateScope();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The AAA (Arrange, Act, Assert) pattern is a common way of writing unit tests for a method under test.

The Arrange section of a unit test method initializes objects and sets the value of the data that is passed to the method under test.

The Act section invokes the method under test with the arranged parameters.

The Assert section verifies that the action of the method under test behaves as expected. For .NET, methods in the Assert class are often used for verification.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Czyli w skrócie można podzielić na 3 sekcje, które są rozdzielane pustą linią

var dbContext = scope.ServiceProvider.GetRequiredService<BookStoreDatabaseContext>();

var client = _factory.CreateClient();

var firstBook = await dbContext.Books.FirstAsync();

var response = await client.GetAsync($"api/BookStore/{firstBook.Id}");
response.EnsureSuccessStatusCode();

var contentString = await response.Content.ReadAsStringAsync();
var book = JsonConvert.DeserializeObject<BookDto>(contentString);
var firstBookDto = _mapper.Map<BookDto>(firstBook);

Assert.NotNull(book);
Assert.Equivalent(firstBookDto, book);
}

[Fact]
public async Task Get_ReturnsNotFoundIfBookDoesntExist()
{
var client = _factory.CreateClient();

var responseInvalid = await client.GetAsync("api/BookStore/11111");
Assert.Equal(HttpStatusCode.NotFound, responseInvalid.StatusCode);
}

[Fact]
public async Task Post_AddsBookToDatabase()
{
var client = _factory.CreateClient();

var book = new CreateBookCommand
{
Title = "Dummy Title",
Author = "Dummy Author",
ReleaseDate = DateTime.Now,
GenreId = 1
};
var bookSerialized = JsonConvert.SerializeObject(book);


var response = await client.PostAsync("api/BookStore",
new StringContent(bookSerialized, Encoding.UTF8, "application/json"));
Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
}

[Fact]
public async Task Post_ReturnsErrorIfNonExistentBookGenre()
{
var client = _factory.CreateClient();

var book = new CreateBookCommand
{
Title = "Dummy Title",
Author = "Dummy Author",
ReleaseDate = DateTime.Now,
GenreId = 123
};
var bookSerialized = JsonConvert.SerializeObject(book);

var response = await client.PostAsync("api/BookStore",
new StringContent(bookSerialized, Encoding.UTF8, "application/json"));
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
}

[Fact]
public async Task Put_UpdateBookInDatabase()
{
var client = _factory.CreateClient();

var book = new BookDto
{
Title = "Dammy Title",
Author = "Dammy Author",
ReleaseDate = DateTime.Now,
GenreId = 1
};
var bookSerialized = JsonConvert.SerializeObject(book);

var response = await client.PutAsync("api/BookStore/1",
new StringContent(bookSerialized, Encoding.UTF8, "application/json"));
Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
}

[Fact]
public async Task Put_ReturnsErrorIfInvalidBookGenre()
{
var client = _factory.CreateClient();

var book = new BookDto
{
Title = "Dammy Title",
Author = "Dammy Author",
ReleaseDate = DateTime.Now,
GenreId = 123
};
var bookSerialized = JsonConvert.SerializeObject(book);

var response = await client.PutAsync("api/BookStore/1",
new StringContent(bookSerialized, Encoding.UTF8, "application/json"));
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
}

[Fact]
public async Task Put_ReturnsNotFoundIfInvalidBookId()
{
var client = _factory.CreateClient();

var book = new BookDto
{
Title = "Dammy Title",
Author = "Dammy Author",
ReleaseDate = DateTime.Now,
GenreId = 123
};
var bookSerialized = JsonConvert.SerializeObject(book);

var response = await client.PutAsync("api/BookStore/11111",
new StringContent(bookSerialized, Encoding.UTF8, "application/json"));
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}

[Fact]
public async Task Delete_DeleteBookFromDatabase()
{
var client = _factory.CreateClient();

var response = await client.DeleteAsync("api/BookStore/1");
Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Można dać asercje na to czy faktycznie zostało usunięte czy nie

}

[Fact]
public async Task Delete_ReturnsNotFoundIfInvalidBookId()
{
var client = _factory.CreateClient();

var response = await client.DeleteAsync("api/BookStore/11111");
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}

[Fact]
public async Task Patch_UpdateBookInDatabase()
{
using var scope = _factory.Services.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<BookStoreDatabaseContext>();

var client = _factory.CreateClient();

var command = new PatchBookCommand
{
Title = "Diummy Book"
};
var commandSerialized = JsonConvert.SerializeObject(command);

var response = await client.PatchAsync("api/BookStore/2",
new StringContent(commandSerialized, Encoding.UTF8, "application/json"));
Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);

var book = await dbContext.Books.FirstOrDefaultAsync(b => b.Id == 2);
Assert.Equal("Diummy Book", book.Title);
}

[Fact]
public async Task Patch_ReturnsNotFoundIfInvalidBookId()
{
var client = _factory.CreateClient();

var command = new PatchBookCommand
{
Title = "Diummy Book"
};
var commandSerialized = JsonConvert.SerializeObject(command);

var response = await client.PatchAsync("api/BookStore/111111",
new StringContent(commandSerialized, Encoding.UTF8, "application/json"));
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
}
Loading