-
Notifications
You must be signed in to change notification settings - Fork 0
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
csskroubledev
wants to merge
1
commit into
main
Choose a base branch
from
codervw
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
add tests #3
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
233
BookStoreAPI.Tests/IntegrationTests/Books/BooksTests.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
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); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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); | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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ą