gpt4 book ai didi

java - 如何使用 JUnit 测试这个类?

转载 作者:行者123 更新时间:2023-11-30 06:08:39 24 4
gpt4 key购买 nike

我必须为这个自动售货类进行单元测试。我开始思考如何做到这一点,但我意识到自动售货类没有带有返回类型的方法(顺便说一句,我只知道如何测试带有返回类型的方法),而且我总是使用断言。

import java.util.Hashtable;

class VendingItem {
double price;
int numPieces;

VendingItem(double price, int numPieces) {
this.price = price;
this.numPieces = numPieces;
}

void restock(int pieces) {
this.numPieces = this.numPieces + pieces;
}

void purchase(int pieces) {
this.numPieces = this.numPieces - pieces;
}
}

/**
* Class for a Vending Machine. Contains a hashtable mapping item names to item
* data, as well as the current balance of money that has been deposited into
* the machine.
*/
public class Vending {
private static Hashtable<String, VendingItem> Stock = new Hashtable<String, VendingItem>();
private double balance;

Vending(int numCandy, int numGum) {
Stock.put("Candy", new VendingItem(1.25, numCandy));
Stock.put("Gum", new VendingItem(.5, numGum));
this.balance = 0;
}

/** resets the Balance to 0 */
void resetBalance() {
this.balance = 0;
}

/** returns the current balance */
double getBalance() {
return this.balance;
}

/**
* adds money to the machine's balance
*
* @param amt
* how much money to add
*/
void addMoney(double amt) {
this.balance = this.balance + amt;
}

/**
* attempt to purchase named item. Message returned if the balance isn't
* sufficient to cover the item cost.
*
* @param name
* The name of the item to purchase ("Candy" or "Gum")
*/
void select(String name) {
if (Stock.containsKey(name)) {
VendingItem item = Stock.get(name);
if (balance >= item.price) {
item.purchase(1);
this.balance = this.balance - item.price;
} else
System.out.println("Gimme more money");
} else
System.out.println("Sorry, don't know that item");
}

}

例如,您认为我如何测试打印某些内容的方法?

最佳答案

这个怎么样:

@Test
public void testResetVendingBalance() {
Vending vending = new Vending(0,0);
vending.addMoney(7);
vending.resetBalance();
assertEquals("Test if vending reset.",0, vending.getBalance(), 0);
}

@Test
public void testAddVendingBalance() {
Vending vending = new Vending(0,0);
vending.addMoney(7);
assertEquals("Test money amount.",7, vending.getBalance(), 0);
}

关于java - 如何使用 JUnit 测试这个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39440117/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com