Can anyone correct my mistake.

Provided code:

public void testSetBaseSalaryNegative() {
        final double altBaseSalary = -999.99;
        try {
            emp.setBaseSalary(altBaseSalary); // Expecting an IllegalArgumentException
            fail ("Negative base-salary values should be rejected by setBaseSalary and result in an IllegalArgumentException");
        } catch (IllegalArgumentException ex) {
            // This is the nominal case
        } catch (RuntimeException ex) {
            assertThrowableTestFailure(ex);

Junit4 is showing this fail.It highlighted
fail ("Negative base-salary values should be rejected by setBaseSalary and result in an IllegalArgumentException");

Here is the code i wrote:

 public void setBaseSalary( double salary ) {
        // TODO: implement this method
        baseSalary = ( salary < 0.0 ) ? 0.0 : salary;
        if (baseSalary < 0.0){
            throw new IllegalArgumentException("Negative base-salary values should be rejected by setBaseSalary and result in an IllegalArgumentException");
        }
    }    

    public double getBaseSalary() {
        // TODO: implement this method
        return baseSalary;

Recommended Answers

All 5 Replies

Line 3 corrects the value of negative salaries to zero before you check for them on line 4

Am i contradicting?

 baseSalary = ( salary < 0.0 ) ? 0.0 : salary;
        if (baseSalary < 0.0){
            throw new IllegalArgumentException("Negative base-salary values should be rejected by setBaseSalary and result in an IllegalArgumentException");

After line 1 baseSalary can never be negative, it will always be either a positive salary value, or zero. So the test on line 2 will always be false.

Typically, if you have a "set" method that does validation, it does all the validation first, before trying to do anything with the values.

Your setBaseSalary() function should be tagged as throwing an exception. IE:

 public void setBaseSalary( double salary ) throws IllegalArgumentException
 {
        // TODO: implement this method
        baseSalary = ( salary < 0.0 ) ? 0.0 : salary;
        if (baseSalary < 0.0)
        {
            throw new IllegalArgumentException("Negative base-salary values should be rejected by setBaseSalary and result in an IllegalArgumentException");
        }
 }

Not specifying that the method throws an exception is an error, and should have been trapped by the compiler.

Your setBaseSalary() function should be tagged as throwing an exception. IE:

No, that's not correct. IllegalArgumentException is a runtime exception a.k.a. unchecked excpetion, and does not have to be declared or caught.

The problem, as I said before, is that line 4 guarantees that the if on line 5 is never true.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.