Pergunta

A seguir é uma classe que eu escrevi em uma aplicação web que estou construindo usando Java Google App Engine. Tenho escrito testes de unidade usando TestNG e todos os testes passam. Eu, então, executar EclEmma em Eclipse para ver a cobertura de teste no meu código. Todas as funções mostram uma cobertura de 100%, mas o arquivo como um todo está mostrando sobre a cobertura de 27%. Onde está o código descoberto 73% vem?

Alguém pode me ajudar a entender como EclEmma funciona e por que estou recebendo a discrepância nos números?

package com.skaxo.sports.models;

import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

@PersistenceCapable(identityType= IdentityType.APPLICATION)
public class Account {

    @PrimaryKey
    @Persistent(valueStrategy=IdGeneratorStrategy.IDENTITY)
    private Long id;

    @Persistent
    private String userId;

    @Persistent
    private String firstName;

    @Persistent
    private String lastName;

    @Persistent
    private String email;

    @Persistent
    private boolean termsOfService;

    @Persistent
    private boolean systemEmails;

    public Account() {}

    public Account(String firstName, String lastName, String email) {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
    }

    public Account(String userId) {
        super();
        this.userId = userId;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getId() {
        return id;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public boolean acceptedTermsOfService() {
        return termsOfService;
    }

    public void setTermsOfService(boolean termsOfService) {
        this.termsOfService = termsOfService;
    }

    public boolean acceptedSystemEmails() {
        return systemEmails;
    }

    public void setSystemEmails(boolean systemEmails) {
        this.systemEmails = systemEmails;
    }
}

Abaixo está o código de teste para a classe acima.

package com.skaxo.sports.models;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.assertFalse;

import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class AccountTest {

    @Test
    public void testId() {
        Account a = new Account();
        a.setId(1L);
        assertEquals((Long) 1L, a.getId(), "ID");
        a.setId(3L);
        assertNotNull(a.getId(), "The ID is set to null.");
    }

    @Test
    public void testUserId() {
        Account a = new Account();
        a.setUserId("123456ABC");
        assertEquals(a.getUserId(), "123456ABC", "User ID incorrect.");
        a = new Account("123456ABC");
        assertEquals(a.getUserId(), "123456ABC", "User ID incorrect.");
    }

    @Test
    public void testFirstName() {
        Account a = new Account("Test", "User", "test@example.com");
        assertEquals(a.getFirstName(), "Test", 
                "User first name not equal to 'Test'.");
        a.setFirstName("John");
        assertEquals(a.getFirstName(), "John", 
                "User first name not equal to 'John'.");
    }

    @Test
    public void testLastName() {
        Account a = new Account("Test", "User", "test@example.com");
        assertEquals(a.getLastName(), "User",
                "User last name not equal to 'User'.");
        a.setLastName("Doe");
        assertEquals(a.getLastName(), "Doe", 
                "User last name not equal to 'Doe'.");
    }

    @Test
    public void testEmail() {
        Account a = new Account("Test", "User", "test@example.com");
        assertEquals(a.getEmail(), "test@example.com", 
                "User email not equal to 'test@example.com'.");
        a.setEmail("john@example.com");
        assertEquals(a.getEmail(), "john@example.com", 
                "User email not equal to 'john@example.com'.");
    }

    @Test
    public void testAcceptedTermsOfService() {
        Account a = new Account();
        a.setTermsOfService(true);
        assertTrue(a.acceptedTermsOfService(),
                "Accepted Terms of Service not true.");
        a.setTermsOfService(false);
        assertFalse(a.acceptedTermsOfService(),
                "Accepted Terms of Service not false.");
    }

    @Test
    public void testAcceptedSystemEmails() {
        Account a = new Account();
        a.setSystemEmails(true);
        assertTrue(a.acceptedSystemEmails(), "System Emails is not true.");
        a.setSystemEmails(false);
        assertFalse(a.acceptedSystemEmails(), "System Emails is not false.");
    }
}
Foi útil?

Solução

Esta é uma suposição, mas com base no Javadoc para PersistenceCapable parece que a classe é tecida com código adicional pelo potenciador JDO para implementar a interface. Se este for o caso, é bem possível que o código adicional não está coberto por seus testes. Se você remover a anotação e executar os testes novamente você vê a cobertura esperado?

Desde o Javadoc:

No Implementação de Referência, o JDO Enhancer modifica a classe para implementar PersistenceCapable antes de carregar a classe no ambiente de tempo de execução. O Enhancer de Referência também adiciona código para implementar os métodos definidos por PersistenceCapable.

Você também pode tentar usar um decompiler como JAD para inspecionar a classe compilada para verificar se a classe é de facto tecida com métodos adicionais no tempo de compilação (ou como um processo de pré). Novamente a partir do Javadoc:

Os métodos extra na interface PersistenceCapable pode ser gerado pelo pré-processamento de um arquivo .java, ou pode ser gerada a partir de uma ferramenta diretamente. A técnica exacta para gerar os métodos extra não é especificado por JDO.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top