1.4-Software-Development-Principles

Simpele Inventarisregistratie System - Slecht weer tests

Je bouwnt een eenvoudig inventarisregistratiesysteem met de volgende functies:

  1. Voeg een product toe aan de inventaris
  2. Verwijder een product uit de inventaris
  3. Werk de voorraad van een product in de inventaris bij
  4. Verkrijg de totale waarde van de inventaris

We geven een implementatie van de basisklassen voor het systeem:

  1. Product - Vertegenwoordigt een product met attributen zoals id, naam, prijs en voorraad.
  2. Inventory - Vertegenwoordigt de inventaris met methoden om producten toe te voegen, te verwijderen, bij te werken en de totale waarde ervan te verkrijgen.

assignment

Maak slecht weer tests voor elke functie van het Inventory System met behulp van JUnit5:

public class Product {
    private String id;
    private String name;
    private int price;
    private int stock;

    public Product(String id, String name, int price, int stock) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.stock = stock;
    }

    // todo: add Getters and setters
}
import java.util.ArrayList;

public class Inventory {
    private ArrayList<Product> products;

    public Inventory() {
        products = new ArrayList<>();
    }

    public void addProduct(Product product) {
        if (product == null || product.getId() == null || product.getId().isEmpty() || product.getName() == null || product.getName().isEmpty() || product.getPrice() < 0 || product.getStock() < 0) {
            throw new IllegalArgumentException("Invalid product.");
        }
        products.add(product);
    }

    public void removeProduct(String productId) {
        Product productToRemove = products.stream().filter(p -> p.getId().equals(productId)).findFirst().orElse(null);
        if (productToRemove == null) {
            throw new IllegalArgumentException("Product not found in inventory.");
        }
        products.remove(productToRemove);
    }

    public void updateProductStock(String productId, int newStock) {
        Product productToUpdate = products.stream().filter(p -> p.getId().equals(productId)).findFirst().orElse(null);
        if (productToUpdate == null) {
            throw new IllegalArgumentException("Product not found in inventory.");
        }
        if (newStock < 0) {
            throw new IllegalArgumentException("Invalid stock value.");
        }
        productToUpdate.setStock(newStock);
    }

    public int getTotalInventoryValue() {
        return products.stream().mapToDouble(product -> product.getPrice() * product.getStock()).sum();
    }
}