Reputation: 1
I write unit test which method using database to check exist record,but when i debug on application it return true,but when debug on unit test it return false,i think i missing some thing like mock from database to create data.i newbie of unit test.pls help me solve it.
public void Test_Exist_Record_Db(TriangleModel triangle, bool regext)
{
//Arrange
bool isExist = false;
//Act
isExist = _repository.IsCalculatedBefore(triangle);
//Assert
Assert.AreEqual(isExist, regext);
}
This method using database
public bool IsCalculatedBefore(TriangleModel triangle)
{
using (var db = new TriangleModelDataContext())
{
var temp =
db.TriangleModels.FirstOrDefault(
x =>
x.LengthSideA ==triangle.LengthSideA &&
x.LengthSideB == triangle.LengthSideB &&
x.LengthSideC == triangle.LengthSideC);
if (temp != null)
{
return true;
}
return false;
}
}
Upvotes: 0
Views: 58
Reputation:
A test called against a real resource, like a database, is called an integration test and not an unit test. In your case you don't need to do an integration test, because you're using the entity framework which is extensively tested by the EF developers.
To solve your problem: I believe, that your connection string in development environment is not the same, than the one in your test environment. The DbContext has a property like Connection (I don't know the exact name, but with IntelliSense or inspecting the object during debugging the test you should be able to find it) with which you can compare the connection strings. But I would rather mock the DbContext. You can read about mocks on Wikipedia.
And, if you didn't knew it, instead of using .FirstOrDefault() and then checking for null, you can use the .Any() method, that returns a boolean, which tells you, if there is a given entry fulfilling the condition.
Upvotes: 1