Add UnitTests for GET in FeedbackReceiversController.cs & FeedbackReceiverService.cs

This commit is contained in:
Denis-Cosmin Nutiu 2021-06-05 17:47:22 +03:00
parent b4021724f2
commit 30ea3ec92c
6 changed files with 150 additions and 15 deletions

View file

@ -1,4 +1,5 @@
using System.Collections.Generic; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
@ -33,7 +34,7 @@ namespace Retroactiune.IntegrationTests.Retroactiune.WebAPI.Controllers
[Fact] [Fact]
public async Task Test_CreateFeedbackReceiver_NoContent() public async Task Test_Create_NoContent()
{ {
var httpResponse = await _client.PostAsync("/api/v1/FeedbackReceivers/", var httpResponse = await _client.PostAsync("/api/v1/FeedbackReceivers/",
new StringContent("[]", Encoding.UTF8, "application/json")); new StringContent("[]", Encoding.UTF8, "application/json"));
@ -41,7 +42,7 @@ namespace Retroactiune.IntegrationTests.Retroactiune.WebAPI.Controllers
} }
[Fact] [Fact]
public async Task Test_CreateFeedbackReceiver_NoName() public async Task Test_Create_NoName()
{ {
// Arrange // Arrange
var fixture = new Fixture(); var fixture = new Fixture();
@ -59,7 +60,7 @@ namespace Retroactiune.IntegrationTests.Retroactiune.WebAPI.Controllers
} }
[Fact] [Fact]
public async Task Test_CreateFeedbackReceiver_NoDescription() public async Task Test_Create_NoDescription()
{ {
// Arrange // Arrange
var fixture = new Fixture(); var fixture = new Fixture();
@ -77,7 +78,7 @@ namespace Retroactiune.IntegrationTests.Retroactiune.WebAPI.Controllers
} }
[Theory, AutoData] [Theory, AutoData]
public async Task Test_CreateFeedbackReceiver_Ok(IEnumerable<FeedbackReceiverInDto> items) public async Task Test_Create_Ok(IEnumerable<FeedbackReceiverInDto> items)
{ {
// Arrange // Arrange
await _mongoDb.DropAsync(); await _mongoDb.DropAsync();
@ -97,7 +98,7 @@ namespace Retroactiune.IntegrationTests.Retroactiune.WebAPI.Controllers
} }
[Fact] [Fact]
public async Task Test_DeleteFeedbackReceiver_ValidationFail() public async Task Test_Delete_ValidationFail()
{ {
// Arrange // Arrange
await _mongoDb.DropAsync(); await _mongoDb.DropAsync();
@ -111,7 +112,7 @@ namespace Retroactiune.IntegrationTests.Retroactiune.WebAPI.Controllers
} }
[Theory, AutoData] [Theory, AutoData]
public async Task Test_DeleteFeedbackReceiver_OK(IEnumerable<FeedbackReceiver> items) public async Task Test_Delete_OK(IEnumerable<FeedbackReceiver> items)
{ {
// Arrange // Arrange
var guids = new List<string>(); var guids = new List<string>();
@ -133,7 +134,7 @@ namespace Retroactiune.IntegrationTests.Retroactiune.WebAPI.Controllers
{ {
var httpResponse = var httpResponse =
await _client.DeleteAsync($"/api/v1/FeedbackReceivers/{guid}", CancellationToken.None); await _client.DeleteAsync($"/api/v1/FeedbackReceivers/{guid}", CancellationToken.None);
Assert.Equal(HttpStatusCode.NoContent, httpResponse.StatusCode); Assert.Equal(HttpStatusCode.NoContent, httpResponse.StatusCode);
} }
// Assert // Assert
@ -141,5 +142,58 @@ namespace Retroactiune.IntegrationTests.Retroactiune.WebAPI.Controllers
.Empty); .Empty);
Assert.Equal(0L, docs); Assert.Equal(0L, docs);
} }
[Fact]
public async Task Test_Get_Ok()
{
// Arrange
await _mongoDb.DropAsync();
var feedbackReceiver = new FeedbackReceiver()
{
Id = new BsonObjectId(new ObjectId(new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 14})).ToString(),
Name = "N4m3",
Description = "someting",
CreatedAt = DateTime.Parse("2020-02-01")
};
await _mongoDb.FeedbackReceiverCollection.InsertManyAsync(new[] {feedbackReceiver});
// Test
var httpResponse =
await _client.GetAsync($"/api/v1/FeedbackReceivers/{feedbackReceiver.Id}", CancellationToken.None);
var item = await httpResponse.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode);
Assert.Equal(
"{\"id\":\"0102030405060708090a0b0e\",\"name\":\"N4m3\",\"description\":\"someting\",\"createdAt\":\"2020-01-31T22:00:00Z\"}",
item);
}
[Fact]
public async Task Test_Get_NotFound()
{
// Arrange
await _mongoDb.DropAsync();
// Test
var httpResponse = await _client.GetAsync("/api/v1/FeedbackReceivers/0102030405060708090a0b0e",
CancellationToken.None);
// Assert
Assert.Equal(HttpStatusCode.NotFound, httpResponse.StatusCode);
}
[Fact]
public async Task Test_Get_BadRequest()
{
// Arrange
await _mongoDb.DropAsync();
// Test
var httpResponse = await _client.GetAsync("/api/v1/FeedbackReceivers/xxx", CancellationToken.None);
// Assert
Assert.Equal(HttpStatusCode.BadRequest, httpResponse.StatusCode);
}
} }
} }

View file

@ -60,5 +60,41 @@ namespace Retroactiune.Tests.Retroactiune.WebAPI.Controllers
mockService.Verify(s => s.DeleteOneAsync("bad_guid_but_unit_test_works_cause_validation_doesnt"), mockService.Verify(s => s.DeleteOneAsync("bad_guid_but_unit_test_works_cause_validation_doesnt"),
Times.Once); Times.Once);
} }
[Fact]
public async Task Get_Successful()
{
// Arrange
var mapper = TestUtils.GetMapper();
var mockService = new Mock<IFeedbackReceiverService>();
mockService.Setup(i => i.FindAsync(It.IsAny<IEnumerable<string>>()))
.ReturnsAsync(new FeedbackReceiver[] {new FeedbackReceiver()});
// Test
var controller = new FeedbackReceiversController(mockService.Object, mapper, null);
var result = await controller.Get("bad_guid_but_unit_test_works_cause_validation_doesnt");
// Assert
Assert.IsType<OkObjectResult>(result);
mockService.Verify(s => s.FindAsync(new[] {"bad_guid_but_unit_test_works_cause_validation_doesnt"}),
Times.Once);
}
[Fact]
public async Task Get_NotFound()
{
// Arrange
var mapper = TestUtils.GetMapper();
var mockService = new Mock<IFeedbackReceiverService>();
// Test
var controller = new FeedbackReceiversController(mockService.Object, mapper, null);
var result = await controller.Get("bad_guid_but_unit_test_works_cause_validation_doesnt");
// Assert
Assert.IsType<NotFoundObjectResult>(result);
mockService.Verify(s => s.FindAsync(new[] {"bad_guid_but_unit_test_works_cause_validation_doesnt"}),
Times.Once);
}
} }
} }

View file

@ -163,5 +163,47 @@ namespace Retroactiune.Tests.Retroactiune.WebAPI.Services
i => i.DeleteOneAsync(It.IsAny<FilterDefinition<FeedbackReceiver>>(), It.IsAny<CancellationToken>()), i => i.DeleteOneAsync(It.IsAny<FilterDefinition<FeedbackReceiver>>(), It.IsAny<CancellationToken>()),
Times.Once()); Times.Once());
} }
[Fact]
public async Task Test_Get_Ok()
{
// Arrange
var mongoDatabaseMock = new Mock<IMongoDatabase>();
var mongoClientMock = new Mock<IMongoClient>();
var mongoSettingsMock = new Mock<IMongoDbSettings>();
var mongoCollectionMock = new Mock<IMongoCollection<FeedbackReceiver>>();
var mongoCursorMock = new Mock<IAsyncCursor<FeedbackReceiver>>();
mongoSettingsMock.SetupGet(i => i.DatabaseName).Returns("MyDB");
mongoSettingsMock.SetupGet(i => i.FeedbackReceiverCollectionName).Returns("feedback_receiver");
mongoClientMock
.Setup(stub => stub.GetDatabase(It.IsAny<string>(), It.IsAny<MongoDatabaseSettings>()))
.Returns(mongoDatabaseMock.Object);
mongoDatabaseMock
.Setup(i => i.GetCollection<FeedbackReceiver>(It.IsAny<string>(), It.IsAny<MongoCollectionSettings>()))
.Returns(mongoCollectionMock.Object);
mongoCollectionMock
.Setup(i => i.FindAsync(It.IsAny<FilterDefinition<FeedbackReceiver>>(),
It.IsAny<FindOptions<FeedbackReceiver, FeedbackReceiver>>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(mongoCursorMock.Object);
// Test
var service = new FeedbackReceiverService(mongoClientMock.Object, mongoSettingsMock.Object);
var guids = new[] {"insert_guid_here"};
await service.FindAsync(guids);
// Assert
mongoClientMock.Verify(i => i.GetDatabase("MyDB", null), Times.Once());
mongoDatabaseMock.Verify(
i => i.GetCollection<FeedbackReceiver>("feedback_receiver", It.IsAny<MongoCollectionSettings>()),
Times.Once());
mongoCollectionMock.Verify(
i => i.FindAsync(It.IsAny<FilterDefinition<FeedbackReceiver>>(),
It.IsAny<FindOptions<FeedbackReceiver, FeedbackReceiver>>(), It.IsAny<CancellationToken>()),
Times.Once);
}
} }
} }

View file

@ -99,7 +99,8 @@ namespace Retroactiune.Controllers
string guid) string guid)
{ {
var result = await _service.FindAsync(new[] {guid}); var result = await _service.FindAsync(new[] {guid});
if (!result.Any()) var feedbackReceivers = result as FeedbackReceiver[] ?? result.ToArray();
if (!feedbackReceivers.Any())
{ {
return NotFound(new BasicResponse() return NotFound(new BasicResponse()
{ {
@ -107,7 +108,7 @@ namespace Retroactiune.Controllers
}); });
} }
return Ok(result.First()); return Ok(feedbackReceivers.First());
} }
[HttpGet] [HttpGet]

View file

@ -8,6 +8,7 @@ namespace Retroactiune
public MappingProfile() public MappingProfile()
{ {
CreateMap<FeedbackReceiver, FeedbackReceiverInDto>().ReverseMap(); CreateMap<FeedbackReceiver, FeedbackReceiverInDto>().ReverseMap();
CreateMap<FeedbackReceiver, FeedbackReceiverOutDto>();
} }
} }
} }

View file

@ -29,18 +29,19 @@ namespace Retroactiune.Services
throw new ArgumentNullException(nameof(items)); throw new ArgumentNullException(nameof(items));
} }
if (!items.Any()) var feedbackReceivers = items as FeedbackReceiver[] ?? items.ToArray();
if (!feedbackReceivers.Any())
{ {
throw new GenericServiceException("items must contain at least one element"); throw new GenericServiceException("items must contain at least one element");
} }
try try
{ {
await _collection.InsertManyAsync(items); await _collection.InsertManyAsync(feedbackReceivers);
} }
catch (Exception e) catch (Exception e)
{ {
throw new GenericServiceException($"Operation failed: {e.Message}"); throw new GenericServiceException($"Operation failed: {e.Message} {e.StackTrace}");
} }
} }
@ -53,7 +54,7 @@ namespace Retroactiune.Services
} }
catch (Exception e) catch (Exception e)
{ {
throw new GenericServiceException($"Operation failed: {e.Message}"); throw new GenericServiceException($"Operation failed: {e.Message} {e.StackTrace}");
} }
} }
@ -68,7 +69,7 @@ namespace Retroactiune.Services
} }
catch (Exception e) catch (Exception e)
{ {
throw new GenericServiceException($"Operation failed: {e.Message}"); throw new GenericServiceException($"Operation failed: {e.Message} {e.StackTrace}");
} }
} }
} }