<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Flavio Magalhães on Medium]]></title>
        <description><![CDATA[Stories by Flavio Magalhães on Medium]]></description>
        <link>https://medium.com/@flaviomata?source=rss-54940397ad5d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mstKmOxHvx-ABT5CVEXFzg.jpeg</url>
            <title>Stories by Flavio Magalhães on Medium</title>
            <link>https://medium.com/@flaviomata?source=rss-54940397ad5d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 12:57:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@flaviomata/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Using ReflectionTestUtils to mock Autowired methods in Java]]></title>
            <link>https://medium.com/@flaviomata/using-reflectiontestutils-to-mock-autowired-methods-in-java-b97595a414a0?source=rss-54940397ad5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b97595a414a0</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[mockito]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Flavio Magalhães]]></dc:creator>
            <pubDate>Wed, 15 Aug 2018 03:46:04 GMT</pubDate>
            <atom:updated>2018-08-15T13:28:44.919Z</atom:updated>
            <content:encoded><![CDATA[<p>Another day while working with tests I faced a problem that make me to use <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/util/ReflectionTestUtils.html"><strong>ReflectionTestUtils</strong></a>. A collection of reflection-based utility of Spring framework that in short, can be used to set attributes into your test stack in runtime, even when they’re privates or inaccessibles.</p><p>First, i’ll context my scenario and show why i decided to try Reflection.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3a9ddd92520f3ba972b911073e3a909/href">https://medium.com/media/f3a9ddd92520f3ba972b911073e3a909/href</a></iframe><p>Consider the Service example method above. I’ve a <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/annotation/Autowired.html"><strong>Autowired</strong> </a>component called appRepository and it’s my <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/stereotype/Repository.html"><strong>Repository</strong></a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25db4ebb20866a99e3a4bb49aec2fe70/href">https://medium.com/media/25db4ebb20866a99e3a4bb49aec2fe70/href</a></iframe><p>With the goal of build a test for <em>methodToTest() </em>of class <em>CollectService</em>, first, I needed:</p><ul><li>mock the return of the private method <em>genListMotives</em>() (line 9)</li><li>mock the return of method <em>findProducts() </em>of <strong>autowired</strong> component (line 11)</li></ul><p>Using mockito in my test class, I declared a <em>CollectService</em> object with the <a href="http://static.javadoc.io/org.mockito/mockito-core/2.21.0/org/mockito/Spy.html"><strong>@Spy</strong></a> annotation, since I needed to simulate the return of the local and private method <em>genListMotives()</em>, while the rest of the object needed to continue as a real instance, to test its behavior.</p><p>So, my first test method looked like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ad25eb8330e384f0febbc3989deaf3d/href">https://medium.com/media/6ad25eb8330e384f0febbc3989deaf3d/href</a></iframe><p>And when I ran the method, I got a NullPointer exception in <strong>appRepository</strong>. It is because the <strong>autowired</strong> component requires an special treatment to be “mocked”.</p><p>Our first option is to declare repository in test class with <strong>@Autowired </strong>annotation and declare context and configuration with propose to inject this dependencies in test class. Like this:</p><pre>@RunWith(SpringRunner.class)<br>@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)<br>@ActiveProfiles(&quot;dsp&quot;)<br>public class RecolhimentoServiceTest {</pre><pre>    ...</pre><pre>}</pre><p>This will initialize the application context, but, if your goal is not a integration test, maybe this is unnecessary, because now, you’ll have a test case with all dependencies of your project loaded (slow test!).</p><p>The correct thing to do here, would be create injection constructors on <em>CollectService</em> so we can pass our instances to private properties no longer<strong> autowired</strong>. But this type of code refactoring is not always easy or safe to do in an already complex class.</p><p>So we have other options that use <a href="https://docs.oracle.com/javase/tutorial/reflect/index.html">reflection mechanism</a> to do this dirty work</p><h3>#1 — Mockito and InjectMocks</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77d9ebeecc4b4c2200e17630aeddf2ff/href">https://medium.com/media/77d9ebeecc4b4c2200e17630aeddf2ff/href</a></iframe><p>Just adding an annotation <strong>@</strong><a href="https://static.javadoc.io/org.mockito/mockito-core/2.21.0/org/mockito/InjectMocks.html"><strong>InjectMocks</strong> </a>in our service will make to our <strong>@Mock</strong>s are injected into service, what our repository includes. And this is works fine.</p><p>But, if you have a test class with another Mocks, they will also be included in service. This can be a problem if you need a different response to each mock in another methods. (This was my case.)</p><h3>#2— ReflectionTestUtils</h3><p>My solution was use this collection of Spring to reflect my mock into my service.</p><pre>ReflectionTestUtils.setField(service, &quot;appRepository&quot;, appRepository);</pre><p>The <em>setField()</em> method receives the parameters: the service object, a string with the name of the field to be replaced on the service object and the value that will be supplied.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58eb2e5272eb5c03e3e3a7c2cf49cdb1/href">https://medium.com/media/58eb2e5272eb5c03e3e3a7c2cf49cdb1/href</a></iframe><p>We find in community some opinions against use Reflection to this <a href="http://pillopl.github.io/constructor-injection/">here</a> and <a href="https://dzone.com/articles/avoid-reflection">here</a>, for example. So I recommend this feature only in specific cases.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b97595a414a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Desenvolvendo rotas inteligentes usando Otimização por Enxame de Partículas]]></title>
            <link>https://medium.com/fcamara-hpt/desenvolvendo-rotas-inteligentes-usando-otimiza%C3%A7%C3%A3o-por-enxame-de-part%C3%ADculas-68085d1b43c0?source=rss-54940397ad5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/68085d1b43c0</guid>
            <category><![CDATA[routing]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[swarm-intelligence]]></category>
            <category><![CDATA[route-optimization]]></category>
            <dc:creator><![CDATA[Flavio Magalhães]]></dc:creator>
            <pubDate>Fri, 12 May 2017 14:55:17 GMT</pubDate>
            <atom:updated>2018-08-15T16:04:39.126Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine que você é um carteiro e precisa entregar todas as cartas da sua bolsa até o fim do expediente as 17:00 horas. Você tem 50 ‘destinos’ a percorrer durante o seu dia.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*WZnUBODRkrvacw8EldaRMg.png" /><figcaption>Problema do caixeiro viajante clássico com 50 pontos.</figcaption></figure><p>Qual seria a menor rota que ligue todos esses destinos e te faz retornar ao ponto de partida? Ou qual a rota que teria um menor custo para ser percorrida?</p><p>Bom, ao se perguntar isso, você acabaria por conhecer involuntariamente o <a href="https://pt.wikipedia.org/wiki/Problema_do_caixeiro-viajante">‘Problema do caixeiro-viajante’,</a> um problema matemático que visa achar a melhor rota possível dentro do seu objetivo.</p><p>Antes que você pense: “Ok, sem problemas. Deixo meu computador verificar <strong>todas</strong> as rotas possíveis dentro desse número de destinos e ele me retornará a melhor delas”. Saiba, que para o nosso exemplo, o número de rotas possíveis é de aproximadamente: <strong>3.0362e+62</strong> !! Ou seja, você precisaria deixar seu computador de lado por dias computando todas esse astronômico número.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/1*wm-X_Yz_qiIBxG7-BwsH7A.png" /><figcaption>Fórmula para calcular número de rotas possíveis.</figcaption></figure><p>Porém, nós estamos somente no começo do dia e precisamos achar uma outra solução para entregar todas essas cartas.</p><p>Para nossa sorte, existem diversos métodos matemáticos que nos auxiliam na resolução (ou minimização) do problema em muito menos tempo.</p><p>Mostraremos aqui a <strong>Otimização por Enxame de Partículas (PSO)</strong>. Onde Marcel P. Caraciolo explica seu conceito brilhantemente <a href="http://aimotion.blogspot.com.br/2009/04/introducao-inteligencia-de-enxame.html"><em>nesse post</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*Cv7o-x4mQQ7BIxN6unKQtg.gif" /><figcaption>Comportamento de enxame comumente encontrado na natureza.</figcaption></figure><p><em>Em resumo, a </em><strong><em>PSO</em></strong><em> visa em simular o comportamento de ‘enxame’ encontrado na natureza em certos tipos de espécie animal, onde, ao se deslocarem de um ponto ao outro, sempre há a existência de um ou mais líderes do bando que acabam influenciando no movimento dos demais.</em></p><p>A estratégia aqui é a seguinte: Determinamos um certo número de indivíduos que terão uma rota candidata a solução do problema, cada um. A partir disso, verificaríamos quem seria o ‘líder do bando’ (vamos chamar de <strong>gbest</strong>), ou seja, aquele indivíduo que tem a melhor rota dentre todos. Sabendo o líder, começamos a ‘cruzar’ (o termo em inglês correto é de ‘crossover’) parte da sua rota com a dos outros indivíduos. Fazendo assim, na teoria, com que todos melhorem sua rota através do líder (melhor indivíduo).</p><p>Há também um segundo ‘crossover’ para cada indivíduo. Porém, nesse, nós misturamos a rota atual de cada indivíduo com a <strong>melhor </strong>rota já obtida pelo mesmo, anteriormente (chamamos de <strong>pbest</strong>).<br>Resumo da ópera: A cada iteração…</p><blockquote>① Escolhemos o líder, dentre os indivíduos. (O que tem melhor resultado).<br>② Fazemos um ‘crossover’ de cada indivíduo com seu <strong>pbest.<br></strong> ③ Com a rota resultante fazemos um outro crossover, mas com o <strong>gbest</strong>.<br>E repetimos o processo na próxima iteração…</blockquote><p>Lembrando, que como a grande maioria dos métodos de otimização bioinspirados nós temos um fator aleatório, e ele aparece no operador ‘crossover’. Portanto, depois do ‘crossover’ a rota resultante pode ser melhor ou pior que a anterior.</p><h4>Achou complicado? Eu te provo que não é!</h4><p>Vamos adotar um exemplo um pouco mais simples. Vamos supor que o nosso problema seja encontrar o melhor caminho que ligue os pontos abaixo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*5DluAX0xtWMuGhZw6-sDCQ.png" /><figcaption>Problema do Caixeiro-viajante para 6 pontos.</figcaption></figure><p>Vamos ter 4 indivíduos candidatos a resolução do problema. E simplesmente sorteamos uma rota diferente para cada um deles. Estamos gerando nesse caso, a <em>população inicial</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*Fnf3pyozIjqv_QsMerTJyQ.png" /><figcaption>A,B,C e D são os indivíduos do nosso problema.</figcaption></figure><p>Vamos então para a <strong>1ª Iteração.<br></strong>Nós calcularemos a distância total das rotas. Com isso, encontraremos o nosso melhor indivíduo, o <strong>gbest.</strong></p><blockquote>A = 38m; B = 30m; C = 32m ; <strong>D = 29m</strong>;</blockquote><p>Logo, nosso <strong>gbest </strong>será o indivíduo ‘D’.<br>Próximo passo é fazer o <strong>crossover</strong>.</p><p>Como estamos na iteração 1 não temos ainda um <strong>pbest </strong>(Já que o pbest é o melhor resultado que cada indivíduo ja teve e ainda estamos na primeira iteração). Por isso o <strong>crossover </strong>na iteração 1 pode ser apenas com o <strong>gbest</strong>, ou seja com o indivíduo ‘D’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*97K5Rhk83zCzmQO5BBQ5tw.png" /><figcaption>Exemplo de crossover entre o gbest (indivíduo D) com o indivíduo A</figcaption></figure><p>O crossover como mostrado acima necessita de 2 fatores aleatórios que aqui vamos chamar de ‘R’ e ‘M’. Considere o primeiro como lugar de corte e o segundo como a quantidade de ‘termos’ que serão passados para o indivíduo.</p><p>Com o R = 3, contamos 3 termos e fazemos uma marcação. Após isso com o M = 2, contamos mais 2 termos e fazemos outra marcação. Os itens que tiverem entra as marcações serão ‘herdados’ para o indivíduo A.</p><p>Esse crossover será feito para <strong>todos </strong>os indivíduos. Cada um com R e M gerados novamente.</p><p>A partir da iteração 2 em diante, nós também faremos um crossover com o <strong>pbest</strong> de cada indivíduo.</p><p>Logo, a sequência do algoritmo fica assim:</p><pre>Passo 1 — Inicialização: Onde definimos o número de indivíduos da nossa população. Definimos também o número de iterações que julgamos necessário.</pre><pre>Passo 2 — Achando o líder: Calcula a distância de todas as rotas para achar o <strong>gbest</strong>.</pre><pre>Passo 3 — Começa as iterações.</pre><pre>Passo 4 — Hora da operação de crossover: É executado o crossover de cada indivíduo com seu <strong>pbest</strong> e <strong>gbest.</strong></pre><pre>Passo 5 — Atualização dos <strong>pbest</strong> e <strong>gbest</strong>:<strong> </strong>Avaliamos a nova rota de cada indivíduo. Ela é melhor que seu pbest atual? Então ele vira o novo pbest. Avaliamos todos os indivíduos. Qual é a melhor rota dessa iteração? Essa será o novo gbest.</pre><pre>Passo 6 — Finalizando as novas rotas: Definimos as rotas resultantes de cada crossover, definindo assim as novas rotas para cada indivíduo.</pre><pre>E repete a partir do passo 3, até o resultado for satisfatório.</pre><p>Entre o passo 5 e o 6 podemos adicionar mais passos com algumas técnicas que pode melhorar a nossa otimização, se tornando variações do PSO clássico. Como Huilian FAN mostra <a href="https://pdfs.semanticscholar.org/63a4/1c7e9db00baacb249668ba112b7cf1830e87.pdf">nesse artigo</a>.</p><p>Pronto. Agora que sabemos como escrever um algoritmo utilizando PSO para resolver nosso problema de rotas, podemos pegar o nosso problema inicial e gerar algo como isso:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*CaIazGWaS_OkRoUXNzQt0A.png" /><figcaption>Problema do caixeiro viajante clássico com 50 pontos.</figcaption></figure><p>Aposto que hoje chegaremos em casa mais cedo.</p><p><em>Usei aqui uma abordagem da PSO para problemas discretos e especificamente para TSP, por isso deixei de fora alguns termos encontrados na literatura , da PSO clássica como ‘fitness’, ‘equação da velocidades’, ‘posição’ e etc. Para um estudo mais aprofundado no assunto, indico os artigos abaixo:</em></p><p><a href="http://www.decom.ufop.br/marcone/Disciplinas/InteligenciaComputacional/OtimizacaoPorNuvemParticulas.pdf">OTIMIZAÇÃO POR NUVEM DE PARTÍCULAS</a><br><a href="https://ai2-s2-pdfs.s3.amazonaws.com/81c8/5e5030c099c90d9e6e5cd93e675e3666c90f.pdf">Particle swarm optimization-based algorithms for TSP and generalized TSP</a><br><a href="http://research.ijcaonline.org/volume47/number15/pxc3880348.pdf">Solving City Routing Issue with Particle Swarm Optimization</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68085d1b43c0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fcamara-hpt/desenvolvendo-rotas-inteligentes-usando-otimiza%C3%A7%C3%A3o-por-enxame-de-part%C3%ADculas-68085d1b43c0">Desenvolvendo rotas inteligentes usando Otimização por Enxame de Partículas</a> was originally published in <a href="https://medium.com/fcamara-hpt">fcamara-hpt</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>