Search code examples
javajunitstatic-variables

Test is not supporting the variable of another class


I have one class shipmentTest

import com.monotonic.Shipment.project.ProductFixture;

public class ShipmentTest  {

    private Shipment shipment = new Shipment();

    @Test
    public void shouldAddItems() throws Exception {
        shipment.add(door); // it is not recognizing door and window objs
        shipment.add(window);

        assertThat(shipment, contains(door, window));
    }

door and window I have imported from ProductFixture class

public static Product door = new Product("Wooden Door", 35);
    public static Product floorPanel = new Product("Floor Panel", 25);
    public static Product window = new Product("Glass Window", 10);

I have made the above objects static so that I can access them directly but in my test class it is not recognizing the variable picked from productFicture class

below is the add method of shipment class

private final List<Product> products = new ArrayList<Product>();

    public void add(Product product) {
        products.add(product);
    }

Can someone please let me know how I can access the door object in my test class without instantiating productFixture class Thank you so much


Solution

  • You need static import in ShipmentTest class.

    Change your import

    import com.monotonic.Shipment.project.ProductFixture;
    

    to

    import static com.monotonic.Shipment.project.ProductFixture.*;
    

    Note that too much static imports are not good from code readability and maintainability view.

    So instead of static import you could just use ProductFixture.door, ProductFixture.floorPanelandProductFixture.window with regular import of ProductFixture in ShipmentTest class.