What kind of tests can I still do in this code?

5

I'm doing a test run in a simple bank application, but I do not know what kind of test I can do in that system to cover 100% of the code, it's only covering 61%. I already did all the tests with lower values, equal and higher, I did with anonymous identification and identified, I did with anonymous identification identified with a lower value, but I do not know which type of test to do to have 100% of the coverage of the code.

link

The codes did not fit the question, so I posted on pastebin.org

Rules Class

RegrasDepositoEnum.java

    package facema.regras;

    import java.math.BigDecimal;

    import facema.modelo.operacional.Deposito;
    import facema.util.StringUtils;

    public enum RegrasDepositoEnum {

        /**
         * O banco não aceita depósitos anônimos, portanto nome e CPF
         * do depositante devem ser fornecidos.
         *
         */
        DADOS_DEPOSITANTE() {
                @Override
                public boolean aplicavel(Deposito deposito) throws Exception {
                        String cpf = deposito.getDepositante().getCpf();
                        String nome = deposito.getDepositante().getNome();

                        if (StringUtils.isStringVazia(cpf) || StringUtils.isStringVazia(nome)) {
                                return false;
                        } else {
                                return true;
                        }
                }
        },

        /**
         * O valor mínimo para depósito é R$ 1,00
         * Depósitos com valores inferiores a este não serão realizados.
         * Retorna false caso o depósito tenha valor inferior a R$ 1,00, então o depósito não pode ser efetuado.
         * Retorna true em caso contrário e o depósito poderá ser efetuado.
         *
         */
        VALOR_MINIMO() {
                @Override
                public boolean aplicavel(Deposito deposito) throws Exception {
                        BigDecimal valor = deposito.getValor();

                        if (valor.compareTo(new BigDecimal("1")) < 0) {
                                return false;
                        } else {
                                return true;
                        }
                }
        };

        public abstract boolean aplicavel(Deposito deposito) throws Exception;

    }

RegrasSaqueEnum.java

    package facema.regras;

    import java.math.BigDecimal;

    import facema.modelo.banco.Conta;
    import facema.modelo.operacional.Saque;

    public enum RegrasSaqueEnum {


        /**
         * Valida se o valor do saque é maior que zero.
         * Retorna true se passar na regra.
         * Retorna false em caso contrário.
         */
        VALIDACAO_VALOR() {
                @Override
                public boolean aplicavel(Saque saque) throws Exception {
                        BigDecimal valor = saque.getValor();

                        if (valor.compareTo(BigDecimal.ZERO) > 0) {
                                return true;
                        } else {
                                return false;
                        }
                }
        },

        /**
         * Limite de R$ 200,00 por dia para saque em uma conta
         * Retorna true se passar na regra.
         * Retorna false em caso contrário.
         */
        LIMITE_DIARIO() {
                @Override
                public boolean aplicavel(Saque saque) throws Exception {
                        Conta conta = saque.getConta();
                        BigDecimal valor = saque.getValor();
                        BigDecimal limite = new BigDecimal("200.00");
                        BigDecimal saqueHoje = conta.getSaqueHoje();

                        BigDecimal saqueTotal = saqueHoje.add(valor);

                        int saqueMaiorLimite = saqueTotal.compareTo(limite);
                        if (saqueMaiorLimite > 0) {
                                return false;
                        } else {
                                return true;
                        }
                }
        },

        /**
         * O valor do saque não pode exceder o valor que o cliente possui na conta
         * Retorna true se passar na regra.
         * Retorna false em caso contrário.
         */
        LIMITE_CONTA() {
                @Override
                public boolean aplicavel(Saque saque) throws Exception {
                        Conta conta = saque.getConta();
                        BigDecimal valor = saque.getValor();

                        int saqueMaiorLimite = valor.compareTo(conta.getSaldo());
                        if (saqueMaiorLimite > 0) {
                                return false;
                        } else {
                                return true;
                        }
                }
        };

        public abstract boolean aplicavel(Saque saque) throws Exception;

    }

RegrasExtratoEnum.java

    package facema.regras;

    import java.util.Date;

    import facema.modelo.operacional.Extrato;

    public enum RegrasExtratoEnum {

        /**
         * Cliente pode solicitar extrato de um período máximo de
         * 1 ano da data inicial até a data final.
         * Caso o intervalo enre as datas inicial e final seja maior que 1 ano, retorna false e o extrato não pode ser fornecido.
         * Caso contrário, retorn true e o extrato é realizado.
         *
         */
        PERIODO_1_ANO() {
                @Override
                public boolean aplicavel(Extrato extrato) throws Exception {
                        Date dataInicial = extrato.getDataFinal();
                        Date dataFinal = extrato.getDataInicial();

                        long dif = Math.abs(dataFinal.getTime() - dataInicial.getTime());
                        long difDias = dif / (24 * 60 * 60 * 1000);

                        if (difDias > 365) {
                                return false;
                        } else {
                                return true;
                        }
                }

        },

        /**
         * O cliente tem direito a 1 extrato mensal gratuito
         * Verifica se o cliente já tirou algum extrato naquela conta gratuitamente no mês corrente.
         * Em caso positivo, o teste retorna false e o extrato deve ser cobrado.
         * Em caso negativo, o teste retorna true e o extrato deve ser gratuito.
         */
        EXTRATO_MENSAL_GRATUITO() {
                @Override
                public boolean aplicavel(Extrato extrato) throws Exception {
                        if (extrato.getConta().getExtratosMes() == 0) {
                                return true;
                        } else {
                                return false;
                        }
                }
        };

        public abstract boolean aplicavel(Extrato extrato) throws Exception;

    }
    
asked by anonymous 25.11.2014 / 13:19

2 answers

2

Code coverage checks to see if all of your code paths have been traversed. This includes verifying all conditional variances.

For example:

if (valor.compareTo(new BigDecimal("1")) < 0) {
  return false;
} else {
  return true;
}

Your tests should cover both the true and false cases.

I tried to check your code, but you did not include all of your system's classes in the question.

A good tool to check the coverage of tests on your code is the JaCoCo . The tool generates a report showing which part of the code is covered or not. It also adds color to the lines of your IDE for easier verification.

Redlinesshowlinesofcodewithoutunittestcoverage.Greenlinesarecodesthatarecoveredbytests.

Report on coverage of tests on all classes of the package. It is possible to observe that some classes are not covered, while others are partially covered.

Finally, it is worth remembering that coverage only means that the code has been executed. It does not guarantee that the code has actually been tested. To create effective tests, you need to create assertions that verify that methods and classes perform as expected.

Update

I was able to run your project in Eclipse. Some considerations.

The JaCoCo tool has several types of code coverage. Coverage by byte code instructions, by conditional variances, by cyclomatic complexity, by lines of code, by methods executed and by instantiated classes.

You can change which type of coverage will be used, as shown below.

Astheimageabove,youcanseethatyourcoveragebylinesofcodeisalmost100%.Inthisview,youcanselectothermetricsandupdateyourtests.Icheckedhereandsometestsaremissing.TakealookatthereportgeneratedinEclipse.

Itisworthrememberingthattheinstructioncoverage,orbytecode,doesnothaveareliablecoveragemetric.AccordingtoJaCoCo:"Not all Java language constructs can be directly compiled to corresponding byte code." In such cases the Java compiler creates synthetic code which sometimes results in unexpected code coverage results. "

That is, some Java constructs are not directly transformed into byte code. The generated code is not covered, generating inconsistencies in the coverage result.

Use metrics such as method calls, run lines, or cyclomatic complexity. Thus, your coverage percentage will be in line with your expectations.

    
25.11.2014 / 16:33
1

Here are some suggestions:

In DEALER_DATA (): Did you try to put invalid CPF in value, but valid in structure? Example 999.999.999.99, try doing this with the "0" because not all masks treat the CPF with 11 "0". You have tested the input letters in place of the CPF. Tested the size of the name field? How many characters he can handle. Tried to fill in the name field with spaces by pressing the spacebar? It will not be null value, just blank value, this error almost no programmer deals with.

END_CURRENT (): Tested negative? Letters? Special characters?

Just looking at this code, my mind popped from tests that can be done ... Try placing a html tag in the fields and typing enter and so on.

    
25.11.2014 / 16:23