简体   繁体   English

如何测试一种方法是否有效?

[英]How can I test if a method has worked or not?

Using the code below, I need to test whether or not the method has been successful in working, and then print "false" if the method has not been successful. 使用下面的代码,我需要测试该方法是否已成功工作,如果该方法未成功,则打印“ false”。

private void doShowBorrower()
    {
        boolean found = false;
        System.out.println("Enter Library Number to Search: ");
        String borrowerLibraryNumber = myScanner.next();
        borrowerList.getBorrower(borrowerLibraryNumber);
    }

I was thinking about using a boolean 'found' which I can set to be true if the method worked properly, and then if it's still false then to print "false". 我在考虑使用布尔值“ found”,如果该方法正常运行,则可以将其设置为true,然后如果它仍然为false,则打印“ false”。

However, I'm not sure how to implement this. 但是,我不确定如何实现这一点。 I'm assuming you need to use loops, but I'm not sure how to do it. 我假设您需要使用循环,但是我不确定该怎么做。

Anyone got an idea? 有人知道吗?

Answer to your question depends on what borrowerList.getBorrower(borrowerLibraryNumber) returns. 对您问题的答案取决于返回的borrowerList.getBorrower(borrowerLibraryNumber)

  • If borrowerList.getBorrower(borrowerLibraryNumber) call returns an object, you can check for Null and if the returned object is null, then you can set the flag to true 如果调用borrowerList.getBorrower(borrowerLibraryNumber)返回一个对象,则可以检查是否为Null,并且如果返回的对象为null,则可以将标志设置为true
  • If borrowerList.getBorrower(borrowerLibraryNumber) call throws an exception when requested object is not found, then you can catch the exception and set the flag to true with in catch block. 如果在未找到请求的对象时,调用rowerList.getBorrower borrowerList.getBorrower(borrowerLibraryNumber)引发异常,则可以捕获异常,并在catch块中将标志设置为true。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM