Test expected an Exception, Exception was thrown (it shows in the output) but test failed anyway

后端 未结 3 1768
一整个雨季
一整个雨季 2021-01-27 07:17

Hi so there\'s a test for a constructor for a vehicle. The test initializes a vehicle with a driver without a driving license and it should throw an Exception. code constructor

相关标签:
3条回答
  • 2021-01-27 07:46

    In your method, you're capturing the exception and logging the message (which is a bad practice, you should log the stacktrace) and in your test you state that the execution of the test must throw a be.vdab.util.mens.MensException without being catched.

    Just re throw it or don't catch it at all in the method/constructor being tested.

    Option 1:

    public Voertuig(/*  ...your arguments here... */) {
        this.nummerplaat = div.getNummerplaat();
        this.Zitplaatsen = Zitplaatsen;
        try {
            //...
            //code in the try...
            //...
        } catch (MensException e) {
            //System.out.println(e.getMessage());
            //use a logger, not System.out
            //in case you still want to use System.out
            //then at least use the code shown below
            //e.printStackTrace(System.out);
            //line above commented since there's no need to log
            //and rethrow the exception
            //the exception will be handled by the highest level execution
            //and there it should be logged or use another strategy
            throw e;
        } 
    }
    

    Option 2:

    public Voertuig(/*  ...your arguments here... */) {
        this.nummerplaat = div.getNummerplaat();
        this.Zitplaatsen = Zitplaatsen;
    //remove the try
    //    try {
        //...
        //code in the try...
        //...
    //remove the catch
    //    } catch (MensException e) {
    //        System.out.println(e.getMessage());
    //    } 
    }
    

    IMO I would use option 2 rather than option 1.

    0 讨论(0)
  • 2021-01-27 07:46

    Here:

        } catch (MensException e) {
            System.out.println(e.getMessage());
        } 
    

    You catch the exception so it is not thrown to the test class.

    Change to to:

    } catch (MensException e) {
        System.out.println(e.getMessage());
        throw e
    } 
    
    0 讨论(0)
  • 2021-01-27 07:51

    You are actually catching the exception in the catch block. That's why your test failed not getting the expected exception.

    0 讨论(0)
提交回复
热议问题