Test with junit

Asked

Viewed 584 times

2

I developed a simple Bank system, now I want to know how I can use Junit only in the ways to withdraw and deposit.

 package CaixaEletronico;

 import java.util.Random;
 import java.util.Scanner;

 public class Caixa {
     public static void main(String[] args){
         // Declarando as variáveis
         String nome;
         double inicial;
         Scanner entrada = new Scanner(System.in);
         Random numero = new Random();
         int conta = 1 + numero.nextInt(9999);

         //Obtendo os dados
         System.out.println("Cadastrando novo cliente.");
         System.out.print("Ente com seu nome: ");
         nome = entrada.nextLine();

         System.out.print("Entre com o valor inicial depositado na conta: ");
         inicial = entrada.nextDouble();

         //Criando a conta
         Conta minhaConta = new Conta(nome, conta, inicial);
         minhaConta.iniciar();
     }
 }

 package CaixaEletronico;
 import java.util.Scanner;

 public class Conta {
     private String nome;
     private int conta, saques;
     private double saldo;
     Scanner entrada = new Scanner(System.in);

     public Conta(String nome, int conta, double saldo_inicial){
         this.nome=nome;
         this.conta=conta;
         saldo=saldo_inicial;
         saques=0;
     }

     public void extrato(){
         System.out.println("\tEXTRATO");
         System.out.println("Nome: " + this.nome);
         System.out.println("Número da conta: " + this.conta);
         System.out.printf("Saldo atual: %.2f\n",this.saldo);
         System.out.println("Saques realizados hoje: " + this.saques + "\n");

     }

     public void sacar(double valor){
         if(saldo >= valor){
             saldo -= valor;
             saques++;
             System.out.println("Sacado: " + valor);
             System.out.println("Novo saldo: " + saldo + "\n");
         } else {
             System.out.println("Saldo insuficiente. Faça um depósito\n");
         }
     }

     public void depositar(double valor)
     {
         saldo += valor;
         System.out.println("Depositado: " + valor);
         System.out.println("Novo saldo: " + saldo + "\n");
     }

     public void iniciar(){
         int opcao;

         do{
             exibeMenu();
             opcao = entrada.nextInt();
             escolheOpcao(opcao);
         }while(opcao!=4);
     }

     public void exibeMenu(){

         System.out.println("\t Escolha a opção desejada");
         System.out.println("1 - Consultar Extrato");
         System.out.println("2 - Sacar");
         System.out.println("3 - Depositar");
         System.out.println("4 - Sair\n");
         System.out.print("Opção: ");

     }

     public void escolheOpcao(int opcao){
         double valor;

         switch( opcao ){
             case 1:    
                     extrato();
                     break;
             case 2: 
                     if(saques<3){
                         System.out.print("Quanto deseja sacar: ");
                         valor = entrada.nextDouble();
                         sacar(valor);
                     } else{
                         System.out.println("Limite de saques diários atingidos.\n");
                     }
                     break;

             case 3:
                     System.out.print("Quanto deseja depositar: ");
                     valor = entrada.nextDouble();
                     depositar(valor);
                     break;

             case 4: 
                     System.out.println("Sistema encerrado.");
                     break;

             default:
                     System.out.println("Opção inválida");
         }
     }
 }

inserir a descrição da imagem aqui

  • https://answall.com/questions/138341/teste-unit%C3%A1rio-com-junit-para-rotinas-default-do-sistema? Rq=1

1 answer

1

In this case, you can check if the method worked as expected by checking the content that is being printed out. To do this, you can create your OutputStream and set it on System.setOut

Following example:

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class ContaTest {

    private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();

    //Aqui você está adicionando o seu outputStream como saída padrão. Quando o comando
    //System.out.println for chamado, o conteúdo será escrito na variável outContent.
    //Dessa forma, você poderá verificar o que está sendo escrito no out.
    @Before
    public void setup() {
        System.setOut(new PrintStream(outContent));
    }

    @After
    public void tearDown() throws IOException {
        outContent.close();
    }

    @Test
    public void testeSacar() {
        //dado (given)
        Conta conta = new Conta("João", 1, 100);

        //quando (when)
        conta.sacar(20);

        //então (then)
        String expected = "Sacado: 20.0\r\nNovo saldo: 80.0\n\r\n";
        Assert.assertEquals(expected, outContent.toString());
    }

    @Test
    public void testeDepositar() {
        //dado (given)
        Conta conta = new Conta("João", 1, 100);

        //quando (when)
        conta.depositar(50);

        //então (then)
        String expected = "Depositado: 50.0\r\nNovo saldo: 150.0\n\r\n";
        Assert.assertEquals(expected, outContent.toString());
    }
}

That stretch "Sacado: 20.0\nNovo saldo: 80.0\n\n" is equal to their System.out.println. Each println is an n, at the end there are two because one is the println and the other is what is in the message itself. In my case is n pq I am using linux. If you are using windows and the test fails, replace n with r n.

The method setup will be called before performing each test and the method teardown will be called after you run each test.

These are simple tests for you to get an idea of how to do. If you want to test multiple inputs in the tested methods, take a look at how to do parameterized tests in junit: https://github.com/junit-team/junit4/wiki/parameterized-tests

  • It is giving error, I would like to carry out the test by System.out.println?

  • What’s the error? The code is just testing System.out.println. You used the class the way it is in the answer?

  • Yes yes, I’ll edit the post and put a print for you see friend

  • The problem is precisely the n I explained in the answer. In linux it is n, but in windows it is r n. I have updated the answer code. Try now again with the updated code.

  • Get, vlw by brother help

  • 1

    If the answer solved the problem, please mark it as solved.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.