1

I'm trying to test a void method using JUnit in NetBeans, my method is changing the value of a double variable and then print the new variable's valur into a TextField, this is my method :

private void calcul(){

        if(operateur.equals("+")){
            chiffre1 = chiffre1 + Double.valueOf(ecran.getText()).doubleValue();
            ecran.setText(String.valueOf(chiffre1));
        }
        if(operateur.equals("-")){
            chiffre1 = chiffre1 - Double.valueOf(ecran.getText()).doubleValue();
            ecran.setText(String.valueOf(chiffre1));
        }          
        if(operateur.equals("*")){
            chiffre1 = chiffre1 * Double.valueOf(ecran.getText()).doubleValue();
            ecran.setText(String.valueOf(chiffre1));
        }     
        if(operateur.equals("/")){
            try{
                chiffre1 = chiffre1 / Double.valueOf(ecran.getText()).doubleValue();
                ecran.setText(String.valueOf(chiffre1));
            } catch(DivisionSurZeroException e) {
                ecran.setText("0");
            }
        }
    }

I Googled about how to test void method but all I can find is void methods that changes the size of a collection.

So please can you give me some idea to start with ? I really don't know what to start with.

  • Use a `get()` method to get the value of the variable you are changing, and use `assert()` with expected result – John Snow Apr 19 '13 at 11:59
  • possible duplicate of [JUNIT testing void methods](http://stackoverflow.com/questions/16043819/junit-testing-void-methods) – Jon Skeet Apr 19 '13 at 11:59
  • 2
    I would refactor the method to separate the calculation and the text field text substitution. Then test the calculation method separately with junit. – Spyros Mandekis Apr 19 '13 at 12:01
  • You could use ReflectionUtils to get the value of the ecran, but in reality, you don't want to test private methods, which is more of a problem here. – Erik Pragt Apr 19 '13 at 12:02

2 Answers2

4

You have to create new entity of tested class and after that call tested function. Later on assert that values have changed as you wanted to.

TestedClass tested = new TestedClass();
tested.calcul();

assertEquals("val", tested.getVal());

However, in your example method is private. To test it you may try to use PowerMock.

srumjant
  • 155
  • 7
1
  1. you could split your method into several smaller methods - one for each operator - and test them independently.

  2. testing void methods is not too different from testing methods with return values:

    1. set up the preconditions
    2. run your method
    3. check the postconditions

in your case:

yourClass.setOperateur("+");
yourClass.setChiffre1(5);
yourClass.setEcran("7");

yourClass.calcul();

assertEquals("12", yourClass.getEcran());
Marco Forberg
  • 2,634
  • 5
  • 22
  • 33