ContextFixture

There's a lot of setup code here and quite a bit of duplication from our previous tests. Luckily, you can use what's known as a Test Fixture.

A Test Fixture is simply some code that is run to configure the system under test. For our purposes, create a ContextFixture to set up an InMemory database.

Create a new class named ContextFixture, which is where all the InMemory database creation will happen:

public class ContextFixture : IDisposable
{
public SpeakerMeetContext Context { get; }

public ContextFixture()
{
var options = new DbContextOptionsBuilder<SpeakerMeetContext>()
.UseInMemoryDatabase("SpeakerMeetContext")
.Options;

Context = new SpeakerMeetContext(options);

if (!Context.Speakers.Any())
{
Context.Speakers.Add(new Speaker {Id = 1, Name = "Test"...});
Context.SaveChanges();
}
}

public void Dispose()
{
Context.Dispose();
}
}

Now, modify the test class to use the new ContextFixture class:

[Collection("Service")]
[Trait("Category", "Integration")]
public class GetAll : IClassFixture<ContextFixture>
{
private readonly IRepository<Speaker> _repository;
private readonly IGravatarService _gravatarService;

public GetAll(ContextFixture fixture)
{
_repository = new Repository<Speaker>(fixture.Context);
_gravatarService = new GravatarService();
}

[Fact]
public void ItExists()
{
var speakerService = new SpeakerService(_repository, _gravatarService);
}
}

 

That's quite a bit cleaner. Now, create a new test to ensure a collection of SpeakerSummary objects is returned when the GetAll method of the SpeakerService is called:

[Fact]
public void ItReturnsCollectionOfSpeakerSummary()
{
// Arrange
var speakerService = new SpeakerService(_repository, _gravatarService);

// Act
var speakers = speakerService.GetAll();

// Assert
Assert.NotNull(speakers);
Assert.IsAssignableFrom<IEnumerable<SpeakerSummary>>(speakers);
}

Next, create a new test class for the Get method of the SpeakerService. The first test should validate that an exception is thrown when a speaker does not exist with the supplied ID:

[Fact]
public void GivenSpeakerNotFoundThenSpeakerNotFoundException()
{
// Arrange
var speakerService = new SpeakerService(_repository, _gravatarService);

// Act
var exception = Record.Exception(() => speakerService.Get(-1));

// Assert
Assert.IsAssignableFrom<SpeakerNotFoundException>(exception);
}

You can reuse the ContextFixture that you created earlier:

[Fact]
public void GivenSpeakerFoundThenSpeakerDetailReturned()
{
// Arrange
var speakerService = new SpeakerService(_repository, _gravatarService);

// Act
var speaker = speakerService.Get(1);

// Assert
Assert.NotNull(speaker);
Assert.IsAssignableFrom<SpeakerDetail>(speaker);
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.49.108