使用JUnit和异常

时间:2015-04-24 03:11:21

标签: eclipse junit

我想在方法的IllegalArgumentException语句中测试while(true)。我尝试过在很多网站上提供的三种方法,但仍然没有弄清楚为什么它不起作用。这是我的测试方法:

public double computeBid(double myHours){
        double dblBogusValue=0;
        double dblNewHours=0;
        double dblMyBid=0;
        double dblMyHours=myHours;

        if(myHours >dblBogusValue){
            dblMyHours=myHours*25; 
            return dblMyHours;
        }
        else{
            Scanner keyboard = new Scanner(System.in);
            System.out.print(this.getStrCompanyName()+" Enter the Hours for the bid:");

            while(true){
                String strEntered = keyboard.next();
                try{
                    dblNewHours=Double.parseDouble(strEntered);

                    if((dblNewHours >0) && (dblNewHours<=120)){ 
                        break;
                    }
                    else{
                        throw new IllegalArgumentException("Enter a Number greater than zero.");
                    }
                }
                catch (IllegalArgumentException e){
            //      System.out.println("Enter a Value in number format from 0 to 120." + e);
                }
            }
        }
        dblMyBid=dblNewHours* 25.00;
        return dblMyBid;
    }

这是测试(我留下了评论,所以你可以看到我的思考过程和其他尝试)

    @Rule public ExpectedException thrown = ExpectedException.none();

    @Test//(expected=IllegalArgumentException.class) //this doen't work as presented.
//  @Test
    public void testAnotherHandyManFailComputeBid() {
        thrown.expect(IllegalArgumentException.class);
        HandyMan handy = new HandyMan();
        System.out.println("Enter a zero or negitive number to cause" +
                 " a IllegalArgumentException.");//Inform testing agent of required action
        handy.computeBid(-1);// force method called to enter test condition
        //(generate exception)
    //provide condition to exit method
        assertEquals(25,handy.computeBid(1),.1);
    }

1 个答案:

答案 0 :(得分:0)

我认为您尝试测试两件事:您的方法是否返回double值并且您的方法是否记录(而不是抛出)IllegalArgumentException?此外,您希望从System.in中读取您需要在测试中提供的用户输入。

您可以使用System Rules与JUnit中的System.in和System.out进行交互。

@Rule
public final TextFromStandardInputStream input = emptyStandardInputStream();

@Rule
public final StandardOutputStreamLog output = new StandardOutputStreamLog();

@Test
public void testAnotherHandyManFailComputeBid() {
    input.provideText("12345");

    HandyMan handy = new HandyMan();
    assertEquals(yourExpectedResult, handy.computeBid(-1));

    assertTrue(output.getLog().contains("IllegalArgumentException"));
}

如果你的方法应该向调用者抛出IllegalArgumentException,那么你应该简单地删除try-catch。