<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: pedro-henrique-arruzzo</title>
    <description>The latest articles on DEV Community by pedro-henrique-arruzzo (@pedro_arruzzo).</description>
    <link>https://dev.to/pedro_arruzzo</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F641927%2Fa5411cae-9a76-40c7-bfc1-60b472c3202b.jpg</url>
      <title>DEV Community: pedro-henrique-arruzzo</title>
      <link>https://dev.to/pedro_arruzzo</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/pedro_arruzzo"/>
    <language>en</language>
    <item>
      <title>TDD and tests with Mocks</title>
      <dc:creator>pedro-henrique-arruzzo</dc:creator>
      <pubDate>Mon, 28 Jun 2021 13:47:24 +0000</pubDate>
      <link>https://dev.to/pedro_arruzzo/tdd-and-tests-with-mocks-52k8</link>
      <guid>https://dev.to/pedro_arruzzo/tdd-and-tests-with-mocks-52k8</guid>
      <description>&lt;h1&gt;
  
  
  TDD
&lt;/h1&gt;

&lt;p&gt;Test Driven Development is a way of developing your code where the test is created before the actual code. This is made to make sure that the development works. The test must be the first thing to be created so the code can be created around it.&lt;/p&gt;

&lt;p&gt;A good way to make these tests is using Mockito.&lt;/p&gt;

&lt;h1&gt;
  
  
  Mockito
&lt;/h1&gt;

&lt;p&gt;Mockito is a mocking framework that is frequently used in unit tests. Mocking an object simulates it's behavior. When this simulation is created, it makes possible to realize a test without the need to call a complex object, we call only the mocked object.&lt;/p&gt;

&lt;h3&gt;
  
  
  Exemples
&lt;/h3&gt;

&lt;p&gt;It's necessary to initiate the mocks before the tests.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Before
public void setup(){
    service = new RentService();
    RentDAO dao = Mockito.mock(RentDAO.class);
    service.setRentDao(dao);
    spcService = Mockito.mock(SPCService.class);
    service.setSpcService(spcService);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I'm simulating the interfaces RentDAO and SPCService with Mockito.&lt;/p&gt;

&lt;p&gt;RentDAO: &lt;code&gt;public void save(Rent rent);&lt;/code&gt;&lt;br&gt;
SPCService: &lt;code&gt;public boolean isNegative(User user);&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;With this we can make our test calling the mock.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Test
public void rentTest() throws Exception {
    //given
    User user = UserBuilder.aUser().now();
    List&amp;lt;Movie&amp;gt; movies = Arrays.asList(MovieBuilder.aMovie().withValue(5.0).now());

    //when
    Rent rent = service.rentMovie(user, movies);

    //then
    error.checkThat(rent.getValue(), is(equalTo(5.0)));
    error.checkThat(DataUtils.isSameDate(rent.getRentDate(), new Date()), is(true));
    error.checkThat(DataUtils.isSameDate(rent.getReturnDate(), DataUtils.obtainDataInDifferenceInDays(1)), is(true));
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this test, a user and a movie where initiated and the rent service was mocked.&lt;/p&gt;

&lt;h4&gt;
  
  
  Conclusion
&lt;/h4&gt;

&lt;p&gt;This way, it's possible to test if the rent service works without actually using it. That's useful to avoid, for example, unnecessary calls to the data base, just mock the object that make this call.&lt;/p&gt;

&lt;p&gt;In case you are interested, here's the repository on GitHub, with more of these mocked tests: &lt;a href="https://github.com/pedro-henrique-arruzzo/poc/tree/main/MockTests"&gt;https://github.com/pedro-henrique-arruzzo/poc/tree/main/MockTests&lt;/a&gt;&lt;/p&gt;

</description>
      <category>tdd</category>
      <category>mockito</category>
      <category>java</category>
      <category>beginners</category>
    </item>
    <item>
      <title>TDD e testes com Mocks</title>
      <dc:creator>pedro-henrique-arruzzo</dc:creator>
      <pubDate>Fri, 25 Jun 2021 17:55:45 +0000</pubDate>
      <link>https://dev.to/pedro_arruzzo/tdd-e-testes-com-mocks-3l4e</link>
      <guid>https://dev.to/pedro_arruzzo/tdd-e-testes-com-mocks-3l4e</guid>
      <description>&lt;h1&gt;
  
  
  TDD
&lt;/h1&gt;

&lt;p&gt;Test Driven Development é uma maneira de desenvolver o seu código onde o teste é criado antes da alteração/criação do código. Isso é feito para que o desenvolvimento tenha a garantia de sua funcionalidade.&lt;/p&gt;

&lt;p&gt;O teste deve ser a primeira coisa a ser feita para que o código seja desenvolvido em volta desse teste para que, ao final do desenvolvimento, o mesmo esteja funcionando, provando que o código funciona.&lt;/p&gt;

&lt;p&gt;Uma boa maneira de realizar estes testes é utilizando o Mockito.&lt;/p&gt;

&lt;h1&gt;
  
  
  Mockito
&lt;/h1&gt;

&lt;p&gt;Mockito é um framework de mocking que é frequentemente usado em&lt;br&gt;
testes de unidade. Mockar um objeto é simular o seu comportamento. Ao criar esta simulação, fica possível realizar um teste sem precisar chamar um objeto complexo, chamamos apenas o mock.&lt;/p&gt;
&lt;h3&gt;
  
  
  Exemplos
&lt;/h3&gt;

&lt;p&gt;É necessário iniciar os mocks antes dos testes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Before
public void setup(){
    service = new RentService();
    RentDAO dao = Mockito.mock(RentDAO.class);
    service.setRentDao(dao);
    spcService = Mockito.mock(SPCService.class);
    service.setSpcService(spcService);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Estou simulando as interfaces RentDAO e SPCService com o Mockito.&lt;/p&gt;

&lt;p&gt;RentDAO: &lt;code&gt;public void save(Rent rent);&lt;/code&gt;&lt;br&gt;
SPCService: &lt;code&gt;public boolean isNegative(User user);&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Com isso podemos realizar o teste chamando o mock.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Test
public void rentTest() throws Exception {
    //given
    User user = UserBuilder.aUser().now();
    List&amp;lt;Movie&amp;gt; movies = Arrays.asList(MovieBuilder.aMovie().withValue(5.0).now());

    //when
    Rent rent = service.rentMovie(user, movies);

    //then
    error.checkThat(rent.getValue(), is(equalTo(5.0)));
    error.checkThat(DataUtils.isSameDate(rent.getRentDate(), new Date()), is(true));
    error.checkThat(DataUtils.isSameDate(rent.getReturnDate(), DataUtils.obtainDataInDifferenceInDays(1)), is(true));
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Neste teste, um usuário e um filme foram iniciados e o serviço de locação foi mockado.&lt;/p&gt;

&lt;h4&gt;
  
  
  Conclusão
&lt;/h4&gt;

&lt;p&gt;Desta maneira, é possível testar se o serviço de locação funciona sem fazer, de fato, uma locação.&lt;br&gt;
Isso é útil para evitar, por exemplo, idas desnecessárias ao banco de dados, basta mockar o objeto que faz a chamada.&lt;/p&gt;

&lt;p&gt;Caso esteja interessado, aqui está o repositório no GitHub com mais testes mockados: &lt;a href="https://github.com/pedro-henrique-arruzzo/poc/tree/main/MockTests"&gt;https://github.com/pedro-henrique-arruzzo/poc/tree/main/MockTests&lt;/a&gt;&lt;/p&gt;

</description>
      <category>tdd</category>
      <category>mockito</category>
      <category>java</category>
      <category>braziliandevs</category>
    </item>
    <item>
      <title>Unit Tests with JUnit</title>
      <dc:creator>pedro-henrique-arruzzo</dc:creator>
      <pubDate>Wed, 16 Jun 2021 12:27:55 +0000</pubDate>
      <link>https://dev.to/pedro_arruzzo/unitary-tests-with-junit-3l12</link>
      <guid>https://dev.to/pedro_arruzzo/unitary-tests-with-junit-3l12</guid>
      <description>&lt;p&gt;Unitary tests are extremely necessary in any application to guarantee its functionality during the development. This tests must be done in a simple and fast way, so they can bem executed many times without taking a long time. Also, they must be independent, which means that one test shouldn't affect the results of another. And they should be repeatable.&lt;br&gt;
These tests must reach to every scenery possible that the application will be used.&lt;/p&gt;

&lt;p&gt;For example, your application offers a service of movie renting. Your tests must simulate this service in many different situations, like, changing quantities, prices, etc.&lt;/p&gt;

&lt;p&gt;Now lets talk a little about JUnit, which is the main tool for the execution of unitary tests.&lt;/p&gt;

&lt;p&gt;JUnit is an extremely important framework, because, with him, we can create tests to verify the functionality of classes and its methods. Besides that, he is responsible for the execution of these tests. This way, every time that the code has been changed, these tests can be executed to guarantee the integrity of the application.&lt;/p&gt;
&lt;h3&gt;
  
  
  Example:
&lt;/h3&gt;

&lt;p&gt;I made a simple code of a movie renting service, and i want to make a test.&lt;/p&gt;

&lt;p&gt;Three entities were created: Movie, Renting and User.&lt;/p&gt;

&lt;p&gt;Here's the RentingService:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class RentService {

    public Rent rentMovie(User user, List&amp;lt;Movie&amp;gt; movies)
            throws FilmeSemEstoqueException, LocadoraException {
        if(user == null) {
            throw new LocadoraException("Empty user");
        }

        if(movies == null || movies.isEmpty()) {
            throw new LocadoraException("Empty movie");
        }

        for (Movie movie : movies) {
            if (movie.getStock() == 0) {
                throw new FilmeSemEstoqueException();
            }
        }

        Rent rent = new Rent();
        rent.setMovies(movies);
        rent.setUser(user);
        rent.setRentDate(new Date());
        Double totalValue = 0d;
        for (Movie movie : movies){
            totalValue += movie.getRentPrice();
        }
        rent.setValue(totalValue);

        //Next day return
        Date returnDate = new Date();
        returnDate = adicionarDias(returnDate, 1);
        rent.setReturnDate(returnDate);

        //Salvando a locacao... 
        //TODO adicionar método para salvar

        return rent;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Now with the entities and the service created we can make the tests.
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Test
    public void rentTest() throws Exception {
        //given
        User user = new User("User 1");
        List&amp;lt;Movie&amp;gt; movies = Arrays.asList(new Movie("Movie 1", 1, 5.0));

        //when
        Rent rent = service.rentMovie(user, movies);

        //then
        error.checkThat(rent.getValue(), is(equalTo(5.0)));
        error.checkThat(isMesmaData(rent.getRentDate(), new Date()), is(true));
        error.checkThat(isMesmaData(rent.getReturnDate(), obterDataComDiferencaDias(1)), is(true));
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;First, we must create the scenery of the test, initializing the entities and giving them a value, we call this "Given".&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;User user = new User("User 1");
List&amp;lt;Movie&amp;gt; movies = Arrays.asList(new Movie("Movie 1", 1, 5.0));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With the "Given" created, we'll make the action we want to test, in this case, rent a movie, we call this "When".&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Rent rent = service.rentMovie(user, movies);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;At last, it's necessary that we verify if everything is working, we call this "Then".&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;error.checkThat(rent.getValue(), is(equalTo(5.0))); error.checkThat(isMesmaData(rent.getRentDate(), new Date()), is(true)); error.checkThat(isMesmaData(rent.getReturnDate(), obterDataComDiferencaDias(1)), is(true));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;With this, it's possible to create tests in different scenarios and make sure your application won't break with an alteration on the code.&lt;/p&gt;

&lt;p&gt;If anyone is interested, the code is on &lt;a href="https://github.com/pedro-henrique-arruzzo/poc/tree/main/UnitTests"&gt;GitHub&lt;/a&gt;&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>junit</category>
      <category>java</category>
    </item>
    <item>
      <title>Testes Unitários com JUnit</title>
      <dc:creator>pedro-henrique-arruzzo</dc:creator>
      <pubDate>Wed, 16 Jun 2021 12:27:10 +0000</pubDate>
      <link>https://dev.to/pedro_arruzzo/testes-unitarios-com-junit-2gi5</link>
      <guid>https://dev.to/pedro_arruzzo/testes-unitarios-com-junit-2gi5</guid>
      <description>&lt;p&gt;Testes são extremamente necessários em qualquer aplicação para garantir sua funcionalidade durante seu desenvolvimento. Esses testes devem ser feitos de forma simples e rápida, para que possam ser executados várias vezes sem levar muito tempo. Além disso, devem ser independentes, ou seja, um teste não deve afetar o outro. E também, deve ser possível repeti-los sempre que for preciso.&lt;br&gt;
Estes testes devem abranger todos os cenários possíveis que a aplicação será usada.&lt;/p&gt;

&lt;p&gt;Por exemplo, sua aplicação oferece um serviço de locação de filmes. Seus testes devem simular este serviço em diversas situações diferentes, ou seja, com diferentes quantidades de produtos, preços diferentes e etc.&lt;/p&gt;

&lt;p&gt;Agora vamos falar um pouco sobre o JUnit, que é a principal ferramenta para a execução de testes unitários.&lt;/p&gt;

&lt;p&gt;JUnit é um framework extremamente importante, pois, com ele, podemos criar testes para verificar funcionalidades de classes e seus métodos. Além disso, ele é responsável por automatizar a execução destes testes. Desta maneira, sempre que houver alguma alteração no código, os testes serão executados para garantir a integridade da aplicação.&lt;/p&gt;
&lt;h3&gt;
  
  
  Exemplo:
&lt;/h3&gt;

&lt;p&gt;Criei um código simples de um serviço de locação de filmes, e quero realizar um teste.&lt;/p&gt;

&lt;p&gt;Três entidades foram criadas: Filme, Locacao, e Usuario.&lt;/p&gt;

&lt;p&gt;LocacaoService:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public Locacao alugarFilme(Usuario usuario, List&amp;lt;Filme&amp;gt; filmes) 
            throws FilmeSemEstoqueException, LocadoraException {
        if(usuario == null) {
            throw new LocadoraException("Usuario vazio");
        }

        if(filmes == null || filmes.isEmpty()) {
            throw new LocadoraException("Filme vazio");
        }

        for (Filme filme: filmes) {
            if (filme.getEstoque() == 0) {
                throw new FilmeSemEstoqueException();
            }
        }

        Locacao locacao = new Locacao();
        locacao.setFilmes(filmes);
        locacao.setUsuario(usuario);
        locacao.setDataLocacao(new Date());
        Double valorTotal = 0d;
        for (Filme filme:filmes){
            valorTotal += filme.getPrecoLocacao();
        }
        locacao.setValor(valorTotal);

        //Entrega no dia seguinte
        Date dataEntrega = new Date();
        dataEntrega = adicionarDias(dataEntrega, 1);
        locacao.setDataRetorno(dataEntrega);

        return locacao;
    }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Agora com as entidades e os serviços criados podemos fazer os testes.
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Test
public void testeLocacao() throws Exception {
    //given
    Usuario usuario = new Usuario("Usuario 1");
    List&amp;lt;Filme&amp;gt; filmes = Arrays.asList(new Filme("Filme 1", 1, 5.0));

    //when
    Locacao locacao = service.alugarFilme(usuario, filmes);

    //then
    error.checkThat(locacao.getValor(), is(equalTo(5.0)));
    error.checkThat(isMesmaData(locacao.getDataLocacao(), new Date()), is(true));
    error.checkThat(isMesmaData(locacao.getDataRetorno(), obterDataComDiferencaDias(1)), is(true));
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Primeiro nós devemos criar o cenário do teste, iniciando as entidades e dando a elas um valor, chamamos isso de "Given".&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Usuario usuario = new Usuario("Usuario 1");
List&amp;lt;Filme&amp;gt; filmes = Arrays.asList(new Filme("Filme 1", 1, 5.0));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Com o cenário criado faremos a ação que desejamos testar, neste caso, alugar um filme, chamamos isso de "When".&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Locacao locacao = service.alugarFilme(usuario, filmes);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Por fim, é necessário verificar se tudo está do jeito certo, chamamos isso de "Then".&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;error.checkThat(locacao.getValor(), is(equalTo(5.0)));
error.checkThat(isMesmaData(locacao.getDataLocacao(), new Date()), is(true));
error.checkThat(isMesmaData(locacao.getDataRetorno(),obterDataComDiferencaDias(1)), is(true));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Conclusão
&lt;/h3&gt;

&lt;p&gt;Com isso é possível criar testes em diversos cenários  e ter certeza que sua aplicação não ira quebrar caso haja algum tipo de alteração no código.&lt;/p&gt;

&lt;p&gt;Caso esteja interessado, o código está no &lt;a href="https://github.com/pedro-henrique-arruzzo/poc/tree/main/UnitTests"&gt;GitHub&lt;/a&gt; &lt;/p&gt;

</description>
      <category>beginners</category>
      <category>junit</category>
      <category>java</category>
      <category>portugues</category>
    </item>
  </channel>
</rss>
