Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439

Theaim of this lab is to review some basic Java programming techniques andto introduce the JUnit testing framework. This tutorial introduces thelatest version, JUnit 4, and its integration in the Eclipse IDE. Thejava files required for this exercise can be downloaded from the linkson this web page.

JUnit is an opensource Java unit testing framework created by Kent Beck and ErichGamma. In this lab exercise, you will learn how to run test cases byJUnit to check the correctness of your code. In Task 2 you will writeyour own JUnit test cases.

Task 1 (Beginners)

  1. Createa new JavaProject called week3 inyour workspace and create a new class (File> New > Class or use the C+ green icon), called BankAccount. Seethe week2 lab for moredetails on how to do this if needed.
  2. Add instance variables int balance and String accountName to class BankAccount to represent the value of theaccount balance, and the name of the customer.   AddJavadoccommentsasyougo,andto check your code regularly using theEclipse formatter and Checkstyle.
  3. Add two more instance variables, int maxBalance and int minBalance to represent some history of the bankaccount.   These variables remember the maximum and minimumbalances ever held by the account since it was created.
  4. Add getter methods to return the value of eachinstance variable. This allows other classes to read (but not change)the values of the instance variable.
  5. Last, make a constructor for the BankAccount. Thisassigns initial values to the instance variables. Yourclass should now look like this one .
  6. Add method signatures for the transactions of a bankaccount: deposit and withdraw, as follows.
    Question: why do we implement both deposit and withdraw methods, notjust one method ?
        public void deposit(int amount) {}
    public void withdraw(int amount) {}
  7. Beforewritingany method code, we will specify what we want the new methodsto do. We have done this using a test program called, .Download this file to your project by clicking on the link and savingthe file to your week3 workspace area. Then Right click on projectweek3 > Refresh to update the files in Eclipse from your workspace.
  8. Warning:ifJUnit4 is not correctly linked to your project, then the fileBankAccoutTest1 will show many errors. To fix this, import JUnit asfollows: rightclick on your project and choose Properties. Select Java Build Path> Add Library > JUnit and select JUnit4 (not 3.8.1) from thelist.    Also, be careful when downloadingthe file that it is saved as a plain text file, not as a web page withHTML tags.
  9. Rightclickon BankAccountTest1.java and Run As > JUnit test. The JUnitwindow shows the number of runs, errors and failures. The test methodslist indicates which test cases have passed with a green tick and whichhave failed with a blue cross. Don�t worry that the test stubs fordeposit and withdraw will fail because you have written no code forthese methods yet.  The given tests will all fail becauseyou have not written any code for these methods yet. So return to yourBankAccount class and add the one line of code required toimplement these methods. Note that the tests provide extra informationabout what is expected: they form part of the documentation forthe class.   For example, the amount deposited or withdrawnmust be non-negative.   Now re-run your tests and you shouldsee a green bar. You can re-run the test set at any time by leftclicking on the green and yellow arrow in the JUnit panel.
  10. Onceyourcode passes all tests, use the Eclipse formatter to correct any layouterrors, and check your BankAccount.java code with Checkstyle, and thensubmit.   There is no need to includefull Javadoc comments (Checkstyle required) in the TEST programs.  Try to make your test cases self documentingwith meaningful names and comments.

Task 2 (Intermediate)

 


  1. Add the followingmethodsignatures to your BankAccount class
        public void chargeInterest(double rate) {}
    public boolean isOverdrawn() { return true; }
  2. Download .Runthetestsbyrightclicking on the test file and select RunAs >JUnit test. Notice that the methods you have not implemented yet willfail.
  3. Themethod isOverdrawn returnsa boolean. Java�s boolean type can take thevalues true or false. When the current bank balance is overdrawn themethod should return true. Otherwise (the balance is 0 or greater) themethod will return false.  
  4. Themethod chargeInterest(double rate) debitsinterest from overdrawnaccounts, depending on the value of the rate parameter. For example, ifthe balance is $-1000, and rate is 0.05, then $50 interest should becharged, resulting in a balance of $-1050.   Non-overdrawnaccounts are unaffected by the chargeInterest method. So, when balanceis $1000 and chargeInterest(0.05) is called, then no interest ischarged so the new balance remains at $1000.
  5. ContinuerunningBankAccountTest2 to check your methods until all tests arepassed and you see the Junit green bar.   Also use Checkstyleand Eclipse formatter to ensure your code meets the required standards.
  6. Onceyourcode passes all tests, use the Eclipse formatter to correct any layouterrors, and check your code with Checkstyle, and then submit.   There is no need to include full Javadoccomments (Checkstyle required) in the TEST programs.  Try to make your test cases self documenting withmeaningful names and comments.

Task 3 (Beginners) Writing JUnit Test Cases


  1. Create a newclass (File > New > Class or use the C+ green icon), called Calculator.
  2. Calculatorhasoneinstance variable, result, thataccumulates the results ofarithmetic operations using integer arithmetic. Create the signaturesfor methods to add, subtract, multiply, divide, square and clear thecalculator. Your class outline should look like this one
  3. Nowyouwill write a simple test class in JUnit4. Eclipse does most of theboring work for you. In the navigation area, right click on your file Calculation.java andselect New > Junit test case. Make sure the radio button at the topis on New JUnit 4 test (not 3.8.1) and tick the stub selections forsetup() and teardown(). The next window allows you to select methods totest. We do not usually test getter or setter methods or theconstructor, so just select the other method, then Finish. This willautomatically create a test for you.
  4. Rightclickon CalculatorTest.java and Run As > JUnit test. There are notests and no code yet, so all the test stubs will fail. But not forlong.
  5. Createacalculator object to test by declaring Calculator c; in the CalculatorTest class andconstructing it in the setUp() methodwith thecommand c = new Calculator(); Thismethod is called before each testcase is run, so you will always have a fresh instance of a calculatorobject for testing.  See the BankAccountTest1 or BankAccountTest2 class for asimilar example.
  6. The addoperation is correct if after adding 4 to a (new) calculatoraccumulator, the result is 4. We express this in JUnit using,
        Calculator c;

    @Before
    public void setUp () throws Exception {
    c = new Calculator();
    }

    @After
    public void tearDown () throws Exception {
    }

    @Test
    public void testAdd () {
    c.add(4);
    assertEquals(4, c.getResult());
    }
  7. Re-runtheJUnit tests using the Green and yellow arrow icon in the JUnitwindow. testAdd still fails, because we have not implemented it yet. Soreturn to your Calculator class,and add some code (always add just theminimum required) to the add method so that it works. You have achievedthis when running JUnit gives a green tick beside the testAdd box.
  8. Repeattheprevious steps for each of the other methods. Always write the testcase first, and then the minimum code required to pass that test.Remember that setUp() is called before each test case is executed, andso you always start with a new Calculator. So, for example, whentesting multiply and divide, use something like,
        c.add(4);
    c.multiply(3);
    assertEquals(12,c.getResult());
  9. Innotime, you should have all green ticks and the famous green bar at thetop of your JUnit window. Now you have a Calculator class plus a testasset  CalculatorTest, which can be used by other programmers tocheck the behaviour of the calculator at any time.  Once your codepasses all tests, use the Eclipse formatter to correct any layouterrors, and check your code with Checkstyle, and thensubmit.   There is no need to include full Javadoc comments(Checkstyle required) in the TEST programs, but try to make your testcases self documenting with meaningful names and comments.

Task 4 (Advanced)


This section contains further optional work forinterested students. Testing exceptions will also be revisited later inthe unit. The tests you have written so far can be thought of as sanitytests. Officially, they are called normal test cases. They test normaloperation of the methods, but do not cover any particularly difficultbehaviour. When testing a class, you must also consider boundary casesand exceptional cases, since these are the areas where errors are mostlikely to occur.

  1. Boundary cases for arithmetic operations includeoperations with positive or negative, zero or very large magnitudeintegers. For example, write a test case to check that the correctresult (0) is returned after you execute the sequence c.add(4);c.multiply(0); 
  2. Division by 0 will cause an ArithmeticException tobe thrown. You can test for exceptions in JUnit4 like this:
        @Test(expected = ArithmeticException.class)
    public void testDivideZero() { c.add(4); c.divide(0); /* this call should throw an exception*/ }
  3. Copy your BankAccount classto a new class, say AdvancedBankAccount.java andwrite a new tester AdvancedBankAccountTest.java tohandle exceptionalcases as you think appropriate.

 

CRICOSProvider Code: 00126G