Sepehr Nazari
Sepehr Nazari

Reputation: 3875

Proper Unit Testing Philosophy

What would be the proper thing to do for each case?

1: Context: Testing a function that creates a database as well as generating metadata for that database

Question: Normally unit test cases are supposed to be independent, but if we want to make sure the function raises an exception when trying to make a duplicate database, would it be acceptable to have ordered test cases where the first one tests if the function works, and the second one tests if it fails when calling it again?

2: Most of the other functions require a database and metadata. Would it be better to call the previous functions in the set up of each test suite to create the database and metadata, or would it be better to hard code the required information in the database?

Upvotes: 0

Views: 102

Answers (2)

Scott Nimrod
Scott Nimrod

Reputation: 11595

Your automated test should model the following:

  1. Setup
  2. Exercise (SUT)
  3. Verify
  4. Teardown

In addition, each test should be as concise as possible and only expose the details that are being tested. All other infrastructure that is required to execute the test should be abstracted away so that the test method serves as documention that only exposes the inputs that are being tested in regards to what you want to verify for that particular test.

Each test should strive to start from a clean slate so that the test can be repeated with the same results each time regardless of the results of prior tests that have been executed.

I typically execute a test-setup and a test-cleanup method for each integration test or any test that depends on singletons that maintain state for the System-Under-Test and need to have it's state wiped.

Upvotes: 1

dkatzel
dkatzel

Reputation: 31648

Normally unit test cases are supposed to be independent, but if we want to make sure the function raises an exception when trying to make a duplicate database, would it be acceptable to have ordered test cases where the first one tests if the function works, and the second one tests if it fails when calling it again?

No, ordered tests are bad. There's nothing stopping you from having a test call another method that happens to be a test though:

@Test
public void createDataBase(){
  ...
}

@Test
public void creatingDuplicateDatabaseShouldFail(){
   createDataBase();
   try{
      //call create again should fail
      //could also use ExpectedException Rule here
      createDataBase();
      fail(...);
   }catch(...){ 
    ...
   }
}

Most of the other functions require a database and metadata. Would it be better to call the previous functions in the set up of each test suite to create the database and metadata, or would it be better to hard code the required information in the database?

If you use a database testing framework like DbUnit or something similar, it can reuse the same db setup over and over again in each test.

Upvotes: 0

Related Questions