Reputation: 58434
I am trying to test my real data by actually hitting the database. I am actually testing my Repository classes. Here is an example of what I am doing;
/// <summary>
/// Summary description for Country
/// </summary>
[TestClass]
public class Country {
public Country() {
_countryRepo = new CountryRepository();
}
private ICountryRepository _countryRepo;
[TestMethod]
public void db_should_return_at_least_one_country_as_approved_all() {
//Act
var model = _countryRepo.GetAll();
//Assert
Assert.IsTrue(model.Count() >= 1);
}
[TestMethod]
public void db_should_return_at_least_one_country_as_approved_true() {
//Act
var model = _countryRepo.GetAll(ApprovalStatus.Approved);
//Assert
Assert.IsTrue(model.Count() >= 1);
}
[TestMethod]
public void db_should_return_Turkey_as_country_name_by_id() {
//Act
var model = _countryRepo.GetSingle(1000);
//Assert
Assert.AreEqual<string>("Turkey", model.CountryName);
}
[TestMethod]
public void db_should_return_Turkey_as_country_name_by_countryISO3166Code() {
//Act
var model = _countryRepo.GetSingle("TR");
//Assert
Assert.AreEqual<string>("Turkey", model.CountryName);
}
[TestMethod]
public void db_should_return_Turkey_as_country_name_by_GUID() {
//Act
var model = _countryRepo.GetSingle(Guid.Parse("9AF174A6-D0F7-4393-AAAD-B168BADEDB30"));
//Assert
Assert.AreEqual<string>("Turkey", model.CountryName);
}
}
This works pretty well for my needs but wondering if I am doing it right by the book. Is there any other patterns that I really should be following here. I do not want to fake my data, my real intense here is to test my DAL and real production data.
Upvotes: 2
Views: 362
Reputation: 364249
You should use static database just for testing and your methods testing GetAll
should assert against real expected count. How do you know that it really returned what you expected if you just assert that it returned at least one record? You should even go through result set and test that all records satisfy the condition (but it is usually used for more complicated conditions).
Upvotes: 0
Reputation: 26772
For the requirement at hand, i.e. data that is really static, and should not be tampered with, I'd say this is a valid approach.
I would recommend to write data-driven tests however, instead of repeating the same test case for each country.
Upvotes: 0
Reputation: 6654
Your tests will fail if someone else (or even you) go to your database and create a new approved country or change your country name. You are going to think: "WTH is wrong with my repository, why is it not working as expected?" But yeah, the problem isn't with the repository.
When I write tests that hit the database I like to create the DB and load default values at startup and destroy then all right after that. I'm not sure if this is the best alternative, but it works pretty well. The problem with this approach is that it's slower and there is more to code.
Upvotes: 2