Shared posts

14 Oct 21:42

Sea Tecnologia - Blog : Utilitários de teste

by brandizzi

E-Plamtax foi um projeto muito positivo que executamos para a Força Aérea. A equipe do E-Plamtax aprendeu muitas coisas no projeto, mas muitas dessas aprendizagens ficaram guardadas conosco. Uma das mais interessantes é a criação de utilitários de teste.

Utilitários de teste são uma maneira de reaproveitar código em testes unitários. Usualmente, isso é feito utilizando os métodos setUp ou @Before dos casos de teste, mas isso tem algumas desvantagens. Por exemplo, em um caso de teste, podemos ter a seguinte inicialização:

    private Address address;
    private AddressDAO addressDAO;

    @Before
    public void setUp() {
        address = new Address();
        address.setStreet("Rua fulano");
        address.setNumber("123/A");
        addressDAO = new AddressDAO();
    }

Se tivermos um teste com o abaixo essa inicialização funciona bem…

    @Test
    public void testGetAllAddresses(){
        addressDAO.addAddress(address);

        List
addresses = addressDAO.getAllAddresses(); assertEquals(1, addresses.size()); assertEquals("Rua fulano", addresses.get(0).getStreet()); assertEquals("123/A", addresses.get(0).getNumber()); }

Agora, se tivermos o teste abaixo, o objeto criado é desperdiçado:

    @Test
    public void testGetNoAddress() {
        List
addresses = addressDAO.getAllAddresses(); assertEquals(0, addresses.size()); }

Se o código for como o seguinte, teremos redundância de código. também temos de decidir SE o outro objeto deve ser criado no @Before também ou no método.

    @Test
    public void testGetAllAddressesMoreThanOne() {
        addressDAO.addAddress(address);
        Address address2 = new Address();
        address2.setStreet("Outra rua");
        address2.setNumber("111");
        addressDAO.addAddress(address2);
        List
addresses = addressDAO.getAllAddresses(); assertEquals(1, addresses.size()); assertEquals("Rua fulano", addresses.get(0).getStreet()); assertEquals("123/A", addresses.get(0).getNumber()); }

Esses inconvenientes são menores quando comparados à tarefa de criar as dependências e um objeto para o teste. Por exemplo, para testar uma classe Person que agrega um Address em um outro caso de teste, teremos de ter um @Before semelhante a esse:

    private Person person;
    private Address address;
    private PersonDAO personDAO;

    @Before     
    public void setUp() {
        address = new Address();
        address.setStreet("Rua fulano");
        address.setNumber("123/A");
        person = new Person();
        person.setName("João");
        person.setAddress(address);
        personDAO = new PersonDAO();
    } 

O código para a criação de endereços replicou-se, e é difícil criar as dependências. Nesses exemplos, vemos casos simples, mas é fácil visualizar como a situação irá se complicar.

Nós solucionamos esse problema criando uma classe para criar esses objetos. Essa classe seria algo como isso:

    public class TestUtil {
        public static Address utilCreateAddress(String street, String number) {
            Address address = new Address();
            address.setStreet("Rua fulano");
            address.setNumber("123/A");
            return address;     
        }

        public static Person utilCreatePerson(String name, Address address) {
            Person person = new Person();
            person.setName(name);
            person.setAddress(address);
            return person;
        }
    }

Nossos casos de teste estendiam a TestUtil, facilitando a criação de objetos:

public class TestAddress2 extends TestUtil {
    private AddressDAO addressDAO = new AddressDAO();

    @Test
    public void testGetAllAddresses() {
        Address address = utilCreateAddress("Rua fulano", "123/A");
        addressDAO.addAddress(address);

        List
addresses = addressDAO.getAllAddresses(); assertEquals(1, addresses.size()); assertEquals("Rua fulano", addresses.get(0).getStreet()); assertEquals("123/A", addresses.get(0).getNumber()); } @Test public void testGetNoAddress() { List
addresses = addressDAO.getAllAddresses(); assertEquals(0, addresses.size()); } @Test public void testGetAllAddressesMoreThanOne() { Address address = utilCreateAddress("Rua fulano", "123/A"); Address address2 = utilCreateAddress("Outra rua", "111"); addressDAO.addAddress(address); addressDAO.addAddress(address2); List
addresses = addressDAO.getAllAddresses(); assertEquals(2, addresses.size()); assertEquals("Rua fulano", addresses.get(0).getStreet()); assertEquals("123/A", addresses.get(0).getNumber()); } }

Como também precisávamos frequentemente de um objeto qualquer, ou que apenas um ou outro parâmetro fosse definido, criávamos variantes dos métodos:

    public static Address utilCreateAddress() {
        return utilCreateAddress("Qualquer", "Qualquer");
    }

    public static Person utilCreatePerson() {
        return utilCreatePerson("José", utilCreateAddress());
    } 

O E-Plamtax foi um projeto um tanto complexo, com grandes redes de dependências de objetos. O uso desses utilitários de teste viabilizou a prática de TDD no sistema. Era emocionante descobrir que, para criar aquele documento que dependia de sete outros documentos e uns cinco ou seis usuários, bastava chamar um método :)

Naturalmente, há mais sobre nossos utilitários de teste do que foi escrito aqui, e pode haver mais ainda que sequer fizemos. (Por exemplo, pode ser interessante produzir utilitários de teste para classes específicas, ao invés de um gigantesco utilitário) Entretanto, como a ideia é bem simples, esperamos que esse pontapé inicial lhe motive a pensar sobre o tema. Até mais!

Let's block ads! (Why?)

15 Jul 18:55

Google Home Ends A Domestic Dispute By Calling The Police

by EditorDavid
An anonymous reader quotes Gizmodo: According to ABC News, officers were called to a home outside Albuquerque, New Mexico this week when a Google Home called 911 and the operator heard a confrontation in the background. Police say that Eduardo Barros was house-sitting at the residence with his girlfriend and their daughter. Barros allegedly pulled a gun on his girlfriend when they got into an argument and asked her: "Did you call the sheriffs?" Google Home apparently heard "call the sheriffs," and proceeded to call the sheriffs. A SWAT team arrived at the home and after negotiating for hours, they were able to take Barros into custody... "The unexpected use of this new technology to contact emergency services has possibly helped save a life," Bernalillo County Sheriff Manuel Gonzales III said in a statement. "It's easy to imagine police getting tired of being called to citizen's homes every time they watch the latest episode of Law and Order," quips Gizmodo. But they also call the incident "a clear reminder that smart home devices are always listening."

Share on Google+

Read more of this story at Slashdot.

15 Jul 18:51

Particle Properties

Each particle also has a password which allows its properties to be changed, but the cosmic censorship hypothesis suggests we can never observe the password itself—only its secure hash.
15 Jul 14:04

Conspiracy Theory

by Doug
15 Jul 14:01

Photo











15 Jul 14:01

Saturday Morning Breakfast Cereal - Dear God

by tech@thehiveworks.com


Click here to go see the bonus panel!

Hovertext:
Later, God starts to wonder if he can trust his own self-perception.

New comic!
Today's News:

Just one week left to get a mega-discount on three books!

15 Jul 14:00

Pizza Party

by nedroid

Pizza Party

15 Jul 13:54

Saturday Morning Breakfast Cereal - It Doesn't Look Good

by tech@thehiveworks.com


Click here to go see the bonus panel!

Hovertext:
His socks and sandals are, on the other hand, exquisite.

New comic!
Today's News:

Just 8 days left to get our new book!

15 Jul 13:51

Laser Sighting

by Doug
15 Jul 13:50

Anésia # 351

by Will Tirando

15 Jul 13:49

Saturday Morning Breakfast Cereal - Advanced

by tech@thehiveworks.com


Click here to go see the bonus panel!

Hovertext:
If I had a PhD in humanities, by God I would wear a labcoat and goggles all day long.

New comic!
Today's News:
15 Jul 13:49

For Sharing:Square-ways | Long-ways











For Sharing:

Square-ways | Long-ways

15 Jul 13:48

webtoon / website / facebook / twitter / patreon

15 Jul 13:42

Quantum

If you draw a diagonal line from lower left to upper right, that's the ICP 'Miracles' axis.
15 Jul 13:41

poppoppop

by Lunarbaboon

09 Jul 18:35

Wildcard Certificates Coming January 2018

Update, January 4, 2018

We introduced a public test API endpoint for the ACME v2 protocol and wildcard support on January 4, 2018. ACME v2 and wildcard support will be fully available on February 27, 2018.

Let’s Encrypt will begin issuing wildcard certificates in January of 2018. Wildcard certificates are a commonly requested feature and we understand that there are some use cases where they make HTTPS deployment easier. Our hope is that offering wildcards will help to accelerate the Web’s progress towards 100% HTTPS.

Let’s Encrypt is currently securing 47 million domains via our fully automated DV certificate issuance and management API. This has contributed heavily to the Web going from 40% to 58% encrypted page loads since Let’s Encrypt’s service became available in December 2015. If you’re excited about wildcard availability and our mission to get to a 100% encrypted Web, we ask that you contribute to our summer fundraising campaign.

A wildcard certificate can secure any number of subdomains of a base domain (e.g. *.example.com). This allows administrators to use a single certificate and key pair for a domain and all of its subdomains, which can make HTTPS deployment significantly easier.

Wildcard certificates will be offered free of charge via our upcoming ACME v2 API endpoint. We will initially only support base domain validation via DNS for wildcard certificates, but may explore additional validation options over time. We encourage people to ask any questions they might have about wildcard certificate support on our community forums.

We decided to announce this exciting development during our summer fundraising campaign because we are a nonprofit that exists thanks to the generous support of the community that uses our services. If you’d like to support a more secure and privacy-respecting Web, donate today!

We’d like to thank our community and our sponsors for making everything we’ve done possible. If your company or organization is able to sponsor Let’s Encrypt please email us at sponsor@letsencrypt.org.

09 Jul 18:10

Comic for July 05, 2017

by Scott Adams
09 Jul 18:08

Ants

by Reza

09 Jul 18:04

Fireflies

by nedroid

Fireflies

09 Jul 18:01

Patterns

by Grant
Adam Victor Brandizzi

Ah, solitude :(



For more comics of visual and personal exploration, check out my new book, The Shape of Ideas! You can order it online here: http://abramsbooks.com/shapeofideas

02 Jul 00:55

Welcome to Work

by Reza

02 Jul 00:54

Robot Jobs

by Doug

Robot Jobs

(With data from willrobotstakemyjob.com.) And here are more careers.

02 Jul 00:47

Emoji Movie

Some other studio should do the Antz/A Bug's Life thing and release The Dingbats Movie at the same time.
02 Jul 00:44

RICKY YOU L’IL SHIT



RICKY YOU L’IL SHIT

02 Jul 00:44

How to Figure Out What Someone Said

by Scott Meyer

I often mutter to myself when I’m thinking things through. Because of this comic, I spent a great deal of time puttering around the house mumbling about wagging my bag.

Hey, by the way, my latest book, Run Program, is out now! It's a book about a rogue AI that has the intelligence of a child. You might think that would make the AI less dangerous, but you'd be wrong. Anyway, I'm quite proud of it. Please check it out, if you have a chance.

As always, thanks for using my Amazon Affiliate links (USUKCanada).

02 Jul 00:43

Comic for June 29, 2017

by Scott Adams
01 Jul 11:24

Comic for 2017.06.24

by Dave McElfatrick
29 Jun 23:16

Saturday Morning Breakfast Cereal - Cheating

by tech@thehiveworks.com


Click here to go see the bonus panel!

Hovertext:
Seriously, babysitting fantasies make zero sense.

New comic!
Today's News:

Last full day to submit for BAHFest Houston!

29 Jun 22:56

What could it be? (by Eat My Paint)







What could it be? (by Eat My Paint)

29 Jun 22:55

by Jeroom Inc.