Skip to content

Instantly share code, notes, and snippets.

@codewithpassion
Created February 21, 2013 08:43
Show Gist options
  • Save codewithpassion/5003277 to your computer and use it in GitHub Desktop.
Save codewithpassion/5003277 to your computer and use it in GitHub Desktop.
Create interfaces for your clases. Depend on the interfaces. Make it testable.
public class Author
{
public string Name { get; set; }
}
public class Book
{
public string Title { get; set; }
}
public interface IAuthorRepository
{
IEnumerable<Author> GetAuthors();
}
public interface IBookRepository
{
IEnumerable<Book> GetBooks();
}
public class LibraryService
{
private readonly IBookRepository _bookRepository;
private readonly IAuthorRepository _authorRepository;
public LibraryService(IBookRepository bookRepository, IAuthorRepository authorRepository)
{
_bookRepository = bookRepository;
_authorRepository = authorRepository;
}
public string GetAllBooksAndAuthors()
{
StringBuilder builder = new StringBuilder();
_bookRepository.GetBooks()
.Select(b => b.Title)
.ToList()
.ForEach(title => builder.AppendFormat("Book title: {0}{1}", title, Environment.NewLine));
builder.AppendLine();
_authorRepository.GetAuthors()
.Select(a => a.Name)
.ToList()
.ForEach(authorName => builder.AppendFormat("Author name: {0}{1}", authorName, Environment.NewLine));
return builder.ToString();
}
}
[TestFixture]
public class LibraryServiceTest
{
private IBookRepository _bookRepository;
private IAuthorRepository _authorRepository;
private LibraryService _testee;
[SetUp]
public void SetUp()
{
_bookRepository = A.Fake<IBookRepository>();
_authorRepository = A.Fake<IAuthorRepository>();
_testee = new LibraryService(_bookRepository, _authorRepository);
}
[Test]
public void GetAllBOoksAndAuthors_ShouldReturnFormatedListOfBooksAndAuthors()
{
//arrange
A.CallTo(() => _bookRepository.GetBooks()).Returns(new [] { new Book { Title = "Clean Code" }, new Book {Title = "The Art of Unit Testing"} });
A.CallTo(() => _authorRepository.GetAuthors()).Returns(new[] { new Author { Name = "Hänsel" }, new Author { Name = "Gretel" }, });
//act
var result = _testee.GetAllBooksAndAuthors();
//assert
result.Should().Be("Book title: Clean Code\r\nBook title: The Art of Unit Testing\r\n\r\nAuthor name: Hänsel\r\nAuthor name: Gretel\r\n");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment