Created
December 17, 2012 12:54
-
-
Save akimboyko/4318084 to your computer and use it in GitHub Desktop.
How to rewrite unittest not to test actual work with database, but works only with mocks
This file contains hidden or 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
void Main() | |
{ | |
// add NUnit and RhinoMocks | |
SomeRule_InsertInfo_WasInserted(); | |
SomeRule_GetInfo_ReciveCorrectInfo(); | |
} | |
// DTO | |
public class Info | |
{ | |
public int Id { get; set; } | |
public string Desc { get; set; } | |
} | |
// Repository incapsulates work with Database | |
public abstract class Repository<T> | |
where T : class | |
{ | |
public abstract void Save(T entity); | |
public abstract IEnumerable<T> GetAll(); | |
} | |
// Class under Test | |
public class SomeRule | |
{ | |
private readonly Repository<Info> repository; | |
public SomeRule(Repository<Info> repository) | |
{ | |
this.repository = repository; | |
} | |
public int InsertInfoToDb(Info oInfo) | |
{ | |
repository.Save(oInfo); | |
return oInfo.Id; | |
} | |
public Info GetInfoFromDb(int id) | |
{ | |
return repository.GetAll().Single(info => info.Id == id); | |
} | |
} | |
// Actual unittests | |
[Test] | |
public void SomeRule_InsertInfo_WasInserted() // ex. InsertInfo | |
{ | |
// Arrange | |
Info oInfo = new Info(); | |
oInfo.Desc = "Some Description here !!!"; | |
var repositoryMock = MockRepository.GenerateStrictMock<Repository<Info>>(); | |
repositoryMock.Expect(m => m.Save(Arg<Info>.Is.NotNull)); | |
// Act | |
var savedrecordid = new SomeRule(repositoryMock).InsertInfoToDb(oInfo); | |
// Assert | |
repositoryMock.VerifyAllExpectations(); | |
} | |
[Test] | |
public void SomeRule_GetInfo_ReciveCorrectInfo() // ex. GetInfo | |
{ | |
// Arrange | |
var expectedId = 1; | |
var expectedInfo = new Info { Id = expectedId, Desc = "Something" }; | |
var repositoryMock = MockRepository.GenerateStrictMock<Repository<Info>>(); | |
repositoryMock.Expect(m => m.GetAll()).Return(new [] { expectedInfo }.AsEnumerable()); | |
// Act | |
Info receivedInfo = new SomeRule(repositoryMock).GetInfoFromDb(expectedId); | |
// Assert | |
repositoryMock.VerifyAllExpectations(); | |
Assert.That(receivedInfo, Is.Not.Null.And.SameAs(expectedInfo)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment