简体   繁体   中英

How to write a test code for a Battery Class?

Write a Battery class that models a rechargeable battery. A battery has a constructor public Battery(float capacity) where capacity is a value measure in milliampere hours. A typical AA battery has a capacity of 2000 to 3000 mAh.

The method public void drain(float amount) drains the capacity of the battery by the given amount. The method public void charge() charges the battery to its original capacity. The method
public float getRemainingCapacity() returns the remaining capacity of the battery. Create a class BatteryTest that exercises the methods of your Battery class.

I need help writing a test for the class. I wrote the code for the class, but I can't figure out how to write a test for it.

public class Battery 

{

float fullCharge = 3000;
float batteryCapacity;

Battery() 
   {
    fullCharge = 3000;
    }

public Battery(float capacity) 
    {

    batteryCapacity = capacity;
    fullCharge = capacity;

     }

public void charge()
    {
    batteryCapacity = fullCharge;
    }

   public void drain(float amount) 
   {
    batteryCapacity = batteryCapacity - amount;
    }

   public float getRemainingCapacity()
   {
    return batteryCapacity;
   }
}

So, I tried writing a test and I got:

 public class BatteryTest
{
 public static void main( String[] args )
 {
  Battery battery = new Battery(2500);

  battery.drain(2500);
  battery.charge();

  float capacity = battery.getRemainingCapacity();


  }

}

But, I'm not really sure. I'm fairly new to this.

A proper test of a class showcases the use of its methods, and demonstrates how those methods handle any boundary cases.
What you have already is very good. I would suggest outputting (System.out.println) the battery's capacity after each method (including the constructor) to show that it has in fact been set to the expected value.
These methods do not have any argument validation, therefore there are no boundary cases to test.

If you were writing a UnitTest, each method of the Battery class would have its own test-method in a test-class that followed these 3 steps:

  1. Setup the data
  2. Invoke the method to be tested
  3. Assert that the actual value is the same as the expected one

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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