user9955719
user9955719

Reputation:

How to create objects in JUnit tests from abstract class

I hava an abstract class Printers and I just want to test its equals method but when I create two Printers in PrintersTest, I cannot instatiate them.

This is PrintersTest:

import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;

class PrintersTest {

    @Test
    void testEqualsObject() {
        Printers a = new Printers("BW_LASER HP", "Laserjet 1230", "25", "180 euros");
        Printers b = new Printers("BW_LASER HP", "Laserjet 1230", "25", "180 euros");
        assertEquals(a,b);
    }       
}

and this is the Printers class:

import java.util.Objects;

public abstract class Printers {
    protected String brand;
    protected String model;
    protected String pages;
    protected String price;

    public Printers(String brand, String model, String pages, String price) { 
        super();
        this.brand = brand;
        this.model = model;
        this.pages = pages;
        this.price = price;
    }

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (!(obj instanceof Printers)) {
            return false;
        }
        Printers other = (Printers) obj;
        return Objects.equals(brand, other.brand) && Objects.equals(model, other.model)
                && Objects.equals(pages, other.pages) && Objects.equals(price, other.price);
    }
}

Thank you so much for your help.

Upvotes: 1

Views: 233

Answers (1)

user10580669
user10580669

Reputation:

You need to have another class extend from printers (probably you already have it) like a type of printer or whatever, then in your test class, you create a new Printer based on that class like this:

@Test
    void testEqualsObject() {
        Printers a = new Bw("BW_LASER HP", "Laserjet 1230", "25", "180 euros");
        Printers b = new Bw("BW_LASER HP", "Laserjet 1230", "25", "180 euros");
        assertEquals(a,b);
    }

That will solve your problem as you will not need to instantiate Printers.

Upvotes: 1

Related Questions