I have a unit test similar to the code snippet below, it should check that the AddUser method only allows unique emails.
My question is around the Arrange
part of this unit test, I use existing system code to setup the first user (class UserLogic
), this is so that I have a user in context to perform the next parts of the test (Act
and Arrange
).
[Fact]
public void CheckUniqueEmail()
{
var context = new DbContext(); //EF Core in memory db
//Arrange
UserLogic userlogic = new UserLogic(context);
User user = new User('[email protected]');
userlogic.AddUser(user);
//Act
UserLogic userlogicNew = new UserLogic(context);
User userNew = new User('[email protected]');
bool result = userlogicNew.AddUser(userNew); //result should be false since this email has already been used
//Assert
Assert.False(result);
}
However, I have seen this done in two ways: The first is as I have done above. The second would be to insert data directly into context, as in the next example
[Fact]
public void CheckUniqueEmail()
{
var context = new DbContext(); //EF Core in memory db
//Arrange
context.Users.Add(new User({Email='[email protected]'}))
context.SaveChanges();
//Act
UserLogic userlogicNew = new UserLogic(context);
User userNew = new User('[email protected]');
bool result = userlogicNew.AddUser(userNew); //result should be false since this email has already been used
//Assert
Assert.False(result);
}
Based on the foregoing, does matter the way I arrange the data for the unit tests? Which one of the two approaches do you think is appropriated for unit tests?
addUser
is compromised, it will compromise the whole test.