Unit Testing Question: Should creating and deleting data be the same method?

I am writing unit tests for a PHP class that supports users in a database. Now I want to check if the user is working, but also when deleting the user. I see several possibilities for this:

  • I write only one method that creates the user and deletes him later
  • I am writing two methods. The first creates the user, saves his identifier. The second deletes this user with the saved identifier.
  • I am writing two methods. The first creates only the user. The second method creates a user, so there is one that can later be deleted.

I read that each test method should be independent of the others, which means that the third option is the way to go, but it also means that each method must independently set its test data (for example, if you want to check if you can add the user twice) .

How would you do that? What is a good unit testing style in this case?

+3
source share
3 answers

Two different things = Two tests.

Test_DeleteUser()may be in another test device, as it has a different code Setup()to ensure that the user already exists.

[SetUp]
public void SetUp() 
{ 
  CreateUser("Me"); 
  Assert.IsTrue( User.Exists("Me"),  "Setup failed!" );
}

[Test]
public void Test_DeleteUser()
{ 
  DeleteUser("Me");
  Assert.IsFalse( User.Exists("Me") );
}

This means that if it Test_CreateUser()passes, but Test_DeleteUser()- no - you know that there is an error in the section of code responsible for deleting users.

. - , Creation , , Delete. , , , Setup " "; ( , , .)

+7

, , Mocks . , 2 .

Test A
  CreateUser("testuser");
  assertTrue(CheckUserInDatabase("testuser"))

Test B
  LoadUserIntoDB("testuser2")
  DeleteUser("testuser2")
  assertFalse(CheckUserInDatabase("testuser2"))

TearDown
  RemoveFromDB("testuser")
  RemoveFromDB("testuser2")

   CheckUserInDatabase(string user)
     ...//Access DAL and check item in DB

mocks stubs, DAL , , , .

+1

, :

. , ( , : ). ( , ). , , , , .

. , " ". , . , 7 15 SQL ( 105 ) , .

The goal is to make the test fail so that you immediately notice the source of the problem. It's like pouring all the restrictions into the code and making them fail earlier so that you know which line of application code you need to check. The main drawback is that these test cases are hell to maintain. Each change in the application code means that you will have to update many of the 105 expected data files.

+1
source

Source: https://habr.com/ru/post/1715055/


All Articles