I am coming from Laravel and new to ASP.net MVC. In Laravel I used to do this to assert if a record was created in database or not:
public function test_a_user_is_created_in_database()
{
// Arrange
// Act
$this->assertDatabaseHas('users', [
'email' => '[email protected]'
]);
}
Is there a way to accomplish the same thing in Xunit?
2
Answers
That is an integration test.
You probably don’t want to do an integration test, typically in .net and unit test, you would use something like FakeItEasy or Moq to provide the correctly typed data, so that the code under test is supplied with the data matching the scenario you want to test in a unit test. If you are testing whether a user is present, you would set it up so that the called to load the data returns the appropriate response, and if you were testing what happens when the user is present you would provide data and calls that return the data appropriate to the user you want to test.
Integration test might be appropriate when integrating a web service, and you don’t quite know for sure what it will return, but if you are using something like dbcontext and entity framework (and you probably should be) then there’s no question about what successfully loading a user should return.
There is probably a more elegant way to accomplish the goal, but this works fine for my purposes:
A reverse of the function is also easily added:
When both are added to a MyCustomAssertions class, they can be called like this:
Note:
Assert.False
toAssert.IsFalse
and the same for True.MySqlCommand
toNpgsqlCommand
andMySqlDataReader
toNpgsqlDataReader
.