Skip to content
Home » Blog » A few words about TDD

A few words about TDD

What TDD is

TDD or Test-Driven Development is a software writing technique that overturns the approach to code development by 180 degrees. I think it is intuitive for us that in order to be able to test something, you must first create it, and then test it. The TDD approach is quite the opposite. We start creating functionality by writing a test, and only then implementing the actual code that will be tested.

There is an established pattern that helps very well to understand how to approach TDD. This scheme is actually a three-phase cycle that is repeated iteratively until the production code meets the required business logic. Here they are:

  • red
  • green
  • refactor
TDD cycle

RED phase - creating a test

This is the phase from which we start the TDD cycle. Its purpose is to write a test that will not pass during testing, and it should always be so at the beginning. We write one small test functionality and then we go to the next phase.

Green phase - creating the actual code

In this phase, implement a MINIMUM amount of production code that will allow you to pass the test. Only when the test turns green, we go to the next phase.

Code Refactoring Phase

This phase consists in bringing the created code, both test and production, to the most "elegant" form. It is important not to neglect this phase because it largely allows you to write an application that is readable for other programmers, and also well-optimized.

After the end of the cycle, we return to the red phase, i.e. writing another small functionality of the test, making the test turn red again. Then we move on to the next phases, until the business logic is correctly implemented and the tests go green.

Why using TDD

Since we already know what the procedure for using the TDD method is, we should consider why use this approach at all. Any writing tests means that you have to write a lot more code, and it does not matter whether you write tests after or before the implementation of the functionality. Nevertheless, the time spent pays off with a vengeance later.

The TDD method allows you to create code that will be easily testable, because we start the test and follow it to its passage. The initial determination of the purpose that the production code is to fulfill makes it easier to write code that will perform well under various boundary conditions, such as passing null values to functions and methods.

Writing a lot of tests allows you to easily catch various bugs that may be difficult to track later. There may be times when you need to make changes to existing code. If you write a lot of tests, you may find that you can save hours of trouble searching for a bug later.

However, in my opinion, the most important advantage of using TDD is the fact that the programmer is forced to write tests, which often recede into the background after writing a working code. TDD enforces a certain rigor of procedure and organizes work. In addition, each passing the test green is a kind of reward and certainly motivates you to continue working in the long run.

A few rules on how to write correctly in TDD

So that all our work devoted to writing tests is not wasted, it is worth applying a few basic rules:

Write unit tests

Unit tests are characterized by the fact that they test a small fragment of the code, and thus perfectly fit the idea of dividing individual implemented functionalities into smaller steps and iteratively adding successive bricks to the code

Apply the given-when-then principle

It is worth following this rule because it organizes the code very well and allows you to easily and quickly understand the functionality that a given test checks.

@Test
void testSummingTwoNumbers() {
 
    //given
    Calculator calculator = spy(Calculator.class);
    given(calculator .getFirstValue()).willReturn(2);
    given(calculator .getSecondValue()).willReturn(3);
 
    //when
    int result = calculator.sumNumbers();
 
    //then
    then(calculator ).should().getFirstValue();
    then(calculator ).should().getSecondValue();
    assertThat(result, equalTo(5));
}

I will cover the above code in more detail in the section on spy, but it clearly shows 3 sections organizing the test.

Call tests intuitively

It is important that the name of the test clearly defines what the test is checking. Don't be afraid to use longer names if necessary. When a test later turns red, it will be easy for you to find the reason why the test failed.

Test after refactoring

It should be remembered that the tests should also be run after the code is refactored. Sometimes, a seemingly small change can inadvertently lead to bugs that will change how your code works.

Have moderation

Especially in the initial fascination with the TDD method, you can overdo the code coverage with tests. Let's not test obvious things such as setters and getters. Remember that the execution of the test usually takes little time, but if we write these tests several hundred or several thousand, running them can be really time-consuming.

Separate the test code from the production code

Remember that the test code should be in a special place for this purpose. Usually, the IDE and the frameworks we work in will make sure that the production code is in the src directory, and the test code is in a separate test directory.

Isolate the tests from the working environment

It is important that the tests are performed in isolation from the environment in which we work. The point is not to reference local files, databases. This is where mock, stub or spy objects come in handy, which you can read about in the following paragraphs.

Mock, Stub, Spy

The title terms refer to the objects that we create in order to test the operation of the methods in the test. They can be called a kind of guinea pigs. What exactly are these objects.

Stub

This is the most primitive way to create an object on which to test. This object is built on the basis of a stub class that is intended to simulate the operation of a real class. It is used, for example, when we do not have access to the real classes, but we know its functioning principle, or when the methods we test require data operation, and as I mentioned earlier, we should isolate the tests from the code work environment.

The disadvantage of using such a solution is that in the case of expanding the class we are testing on, we must also expand the stub class as needed.

mock

Mock is an object type that is automatically generated based on the class we want to test. Usually, to use mocks, additional libraries are required, such as Mockito for Java. The method of creating an object is very simple, and in the case of Mockito it may look like this:

MySampleClass mySampleClass= mock(mySampleClass.class);

This one line of code causes a new object to be created, the fields of which are filled with simple data, such as 0 values for integer fields. The advantage of this solution is that we do not have to create separate classes for testing purposes. mockujemy is automatically taken into account when creating a mock. In addition, libraries such as Mockito give us many tools to check what parameters were used when calling a given method or count, for example, the number of times a given method was called.

Spy

It is a kind of combination of mock and stuba. Its main advantage is that it gives the programmer flexibility because it is created on the basis of the class that we simulate, but we can impose, for example, what values each method should return and use them later to test another method.

@Test
void testSummingTwoNumbers() {
 
    //given
    Calculator calculator = spy(Calculator.class);
    given(calculator .getFirstValue()).willReturn(2);
    given(calculator .getSecondValue()).willReturn(3);
 
    //when
    int result = calculator.sumNumbers();
 
    //then
    then(calculator ).should().getFirstValue();
    then(calculator ).should().getSecondValue();
    assertThat(result, equalTo(5));
}

In the above code, we simulated returning values from getters, and then we used the obtained values to test the code that sums two numbers in the sumNumbers () method:

int sumNumbers(){
    return getFirstValue() + getSecondValue();
}

Each of the methods shown has its advantages and disadvantages, but they provide a wide range of possibilities and are a real improvement in writing application tests.

1 thought on “O TDD słów moich kilka”

  1. Pingback: WetApp - Szybka Prognoza Pogody – Wojciech Siwek

Comments are closed.

W celu świadczenia usług na najwyższym poziomie stosuję pliki cookies, które będą zamieszczane w Państwa urządzeniu (komputerze, laptopie, smartfonie). W każdym momencie mogą Państwo dokonać zmiany ustawień Państwa przeglądarki internetowej i wyłączyć opcję zapisu plików cookies. Ze szczegółowymi informacjami dotyczącymi cookies na tej stronie można się zapoznać tutaj: View more
Cookies settings
Akceptuj
Blokuj
Privacy policy
Privacy & Cookies policy
Cookie name Active

The privacy policy describes the rules for the processing of information about you, including personal data and cookies, i.e. cookies.


1. General information

  1. This policy applies to the website operating at the url address: www.wojciechsiwek.pl
  2. The website operator and the personal data administrator is: Wojciech Siwek
  3. The operator's e-mail contact address: wojciech.siwek.programista@gmail.com
  4. The operator is the Administrator of your personal data in relation to the data provided voluntarily on the Website.
  5. The website uses personal data for the following purposes:
    • Running a comment system
    • Handling inquiries via the form
  6. The website obtains information about users and their behavior in the following way:
    1. Through data entered voluntarily in forms, which are entered into the Operator's systems.
    2. By saving cookie files in end devices (so-called "cookies").

2. Selected data protection methods used by the Operator

  1. The places of logging in and entering personal data are protected in the transmission layer (SSL certificate). As a result, personal data and login data entered on the website are encrypted on the user's computer and can only be read on the target server.
  2. User passwords are stored in a hashed form. The hash function works in one direction - it is not possible to reverse its operation, which is now a modern standard in the field of storing user passwords.
  3. The operator periodically changes his administrative passwords.
  4. In order to protect data, the Operator regularly makes backup copies.
  5. In order to protect data, an essential element of data protection is regular updating of all software used by the Operator to process personal data, which in particular means regular updates of programming components. The Operator regularly makes backup copies.

3. Hosting

  1. The website is hosted (technically maintained) on the operator's server: NETMARK.

4. Your rights and additional information on how to use the data

  1. In some situations, the Administrator has the right to transfer your personal data to other recipients if it is necessary to perform the contract concluded with you or to fulfill the obligations incumbent on the Administrator. This applies to such groups of recipients:
    • postal operators
    • comment system operators
    • authorized employees and associates who use the data to achieve the purpose of the website
  2. Your personal data processed by the Administrator for no longer than it is necessary to perform the related activities specified in separate regulations (e.g. on accounting). With regard to marketing data, the data will not be processed for more than 3 years.
  3. You have the right to request from the Administrator:
    • access to your personal data,
    • rectifying them,
    • deletion,
    • processing restrictions,
    • and data portability.
  4. You have the right to object to the processing indicated in point 3.3 c) to the processing of personal data in order to perform the legitimate interests pursued by the Administrator, including profiling, while the right to object may not be exercised if there are valid legally justified grounds for processing of your interests, rights and freedoms, in particular establishing, investigating or defending claims.
  5. The Administrator's actions may be appealed against to the President of the Personal Data Protection Office, ul. Stawki 2, 00-193 Warsaw.
  6. Providing personal data is voluntary, but necessary to operate the Website.
  7. In relation to you, actions may be taken consisting in automated decision making, including profiling to provide services under the concluded contract and for the purpose of conducting direct marketing by the Administrator.
  8. Personal data is not transferred from third countries within the meaning of the provisions on the protection of personal data. This means that we do not send them outside the European Union.

5. Information in the forms

  1. Serwis zbiera informacje podane dobrowolnie przez użytkownika, w tym dane osobowe, o ile zostaną one podane.
  2. The website may save information about connection parameters (time stamp, IP address).
  3. The website, in some cases, may save information facilitating the linking of data in the form with the e-mail address of the user filling in the form. In this case, the user's e-mail address appears inside the url of the page containing the form.
  4. The data provided in the form is processed for the purpose resulting from the function of a specific form, eg to process the service request or commercial contact, service registration, etc. Each time the context and description of the form clearly informs what it is used for.

6. Administrator logs

  1. Information on the behavior of users on the website may be subject to logging. These data are used to administer the website.

7. Relevant marketing techniques

  1. The operator uses statistical analysis of website traffic through Google Analytics (Google Inc. based in the USA). The operator does not provide personal data to the operator of this service, but only anonymised information. The service is based on the use of cookies on the user's end device. In terms of information about user preferences collected by the Google advertising network, the user can view and edit information derived from cookies using the tool: https://www.google.com/ads/preferences/

8. Information about cookies

  1. The website uses cookies.
  2. Cookie files (so-called "cookies") are IT data, in particular text files, which are stored on the Website User's end device and are intended for using the Website's pages. Cookies usually contain the name of the website they come from, the storage time on the end device and a unique number.
  3. The entity that places cookies on the Website User's end device and obtains access to them is the Website operator.
  4. Cookies are used for the following purposes:
    1. maintaining the Website user's session (after logging in), thanks to which the user does not have to re-enter the login and password on each subpage of the Website;
    2. achieving the goals set out above in the section "Important marketing techniques";
  5. The Website uses two basic types of cookies: session cookies and persistent cookies. Session cookies are temporary files that are stored on the User's end device until logging out, leaving the website or turning off the software (web browser). Persistent cookies are stored on the User's end device for the time specified in the cookie file parameters or until they are deleted by the User.
  6. Software for browsing websites (web browser) usually allows cookies to be stored on the User's end device by default. Website Users can change the settings in this regard. The web browser allows you to delete cookies. It is also possible to automatically block cookies.Detailed information on this subject can be found in the help or documentation of the web browser.
  7. Restrictions on the use of cookies may affect some of the functionalities available on the Website pages.
  8. Cookies placed on the Website User's end device may also be used by entities cooperating with the Website operator, in particular the following companies: Google (Google Inc. based in the USA), Facebook (Facebook Inc. based in the USA), Twitter (Twitter Inc. based in the USA).

9. Managing cookies - how to express and withdraw consent in practice?

  1. If the user does not want to receive cookies, he may change the browser settings. We reserve that disabling cookies necessary for authentication processes, security, maintaining user preferences may make it difficult, and in extreme cases may prevent the use of websites.
  2. In order to manage cookie settings, select the web browser you use from the list below and follow the instructions:
Save settings
Cookies settings