D
D
Daniel2018-01-29 21:58:39
Java
Daniel, 2018-01-29 21:58:39

What does a real JUNIT test example look like?

For the umpteenth time I want to deal with the tests, and for the life of me, I can’t understand why they are better than a simple system.out.print(). No matter how many times I wrote tests, firstly I spent more time, and secondly, I ALWAYS got a true result. Moreover, I always knew the already known result in advance, I always knew that 2+2==4. Or in general I use a copy of the file in the test files, there I define the mainTest c main class and in it I make an example of the functioning of the class, but this is some kind of demonstration of the possibilities, not testing. It doesn't seem complicated, but I don't understand how to make them .

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
Sergey Gornostaev, 2018-01-29
@daniil14056

You only notice the benefit of tests when you start writing something more complicated than hello worlds. They are especially visible when the application has been developed for several years and by more than a dozen developers. You change some part of the code, start testing and see that now another section of the code does not pass the test, because last year a developer whom you did not even meet had an abstraction leak.

O
Oleg, 2018-01-31
@Symbol7

As Sergei Gornostaev said , the benefits of unit tests can only be seen in a serious and large project, as well as with automatic project builds. The task of Unit tests is to check whether the logic of the method under test is executed correctly and whether it returns the expected result. It is advisable not to go beyond the class under test, that is, if the class uses some external resources or other classes, then it is worth emulating (locking) these resources and classes, since they must be tested by separate tests. Thus, we only test the code of a particular class, knowing in advance what other classes will return to us.
Let's say we have some kind of book mapper from a DB entity to a DTO object. A book repository is injected into this mapper, from which you can get a book by id.

public class BookMapper {
    @Inject
    private BookRepository bookRepository;

    public BookDTO mapToDTO(Integer id){
        Book book = bookRepository.findOne(id);
        return new BookDTO(book.getId(), book.getName());
    }
}

Our task is to test the logic of this mapper. We can lock the repository, since we are not testing it now (there should be separate tests for it), and check if the mapper will return the necessary DTO to us if some id is passed to it. Set up a mock repository and call the desired method. Then we compare the expected result with the result obtained:
@RunWith(MockitoJUnitRunner.class)
public class BookMapperTest {
    @Mock
    private BookRepository bookRepository;

    @InjectMocks
    private BookMapper bookMapper;

    @Test
    public void testMapToDTO() {
        // Мокаем репозиторий. Он возвращает конкретную книгу при передаче ему
        // конкретный id
        Book book = new Book(20, "Конституция");
        Mockito.when(bookRepository.findOne(20)).thenReturn(book);

        // Ожидаемая книга
        BookDTO expectedBook = new BookDTO(20, "Конституция");

        // Полученная из маппера книга
        BookDTO actualBook = bookMapper.mapToDTO(20);

        // Сравниваем ожидаемую книгу и полученную книгу
        Assert.assertEquals(expectedBook, actualBook);
    }
}

This is a very exaggerated example. But now we can be sure that if someone ever changes the mapper class so that it starts returning a different result, then the test will fail, which will indicate that other classes using this mapper can also potentially have mistake.
In this case, the example is quite simple. On real code, you need to test all the unique scenarios of the method. For example, if a method has an if branch, switch iteration, throwing an exception, etc., then you need to test each option.

K
kzoper, 2018-01-30
@kzoper

1. You check the correct operation of the function.
2. How it handles errors.

Y
Yerlan Ibraev, 2018-01-30
@mad_nazgul

You are confusing TDD and unit testing a bit.
These things are perpendicular.
TDD is a way (methodology) of software development.
And there, yes, at the beginning of the test (unit-test) should be red.
Unit-test is just a tool, like a debugger.
The debugger is also easily replaced by system.out.print()
:-)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question