Spades
Spades

Reputation: 23

JUnit trying to test a valid input to see if it returns the correct value

I'm trying to test getPoints to check if it returns the right value using Junit5 testing.

public class Grade {
    private final int points;

    public int getPoints() {
        return points;
    }

    public Grade(int p) throws IllegalArgumentException {
        if(p<1 || p>20) 
            throw new IllegalArgumentException();
        points = p;
    }
}

Currently the test I have is:

@Test
    void PointReturnTest() {
        int p = 15;
        assertSame(p,p);
    }

I don't think I'm actually testing the getPoints since it isn't linking to my Junit test above ^. Reason I ask is because when I enter:

 int p = 30;
        assertSame(p,p);

The Junit test still passes when it isn't valid since

if(p<1 || p>20) 

Is there a better way to test this ?

Edit: Currently this is what I have:

@Test
    void PointReturnTest() {
        int p = 15;
        Grade grade = new Grade(p);
        assertEquals(p, p.getPoints());
    }

But the concern is that it says: "Cannot invoke getPoints() on the primitive type int"

Upvotes: 1

Views: 398

Answers (2)

Daniel Scerpa
Daniel Scerpa

Reputation: 76

with your code:

@Test
    void PointReturnTest() {
        int p = 15;
        assertSame(p,p);
    }

the assert compare 15 with 15.. p is local and is not the p inside Grade.

And for that reason you can't write:

@Test
    void PointReturnTest() {
        int p = 15;
        Grade grade = new Grade(p);
        **assertEquals(p, p.getPoints());**
    }

p is the local variable (int)... write grade.getPoints(). as already suggested

Upvotes: 0

Matt Vickery
Matt Vickery

Reputation: 121

Perhaps you’re looking for something like this?

@Test
void PointReturnTest() {
    int p = 15;
    Grade grade = new Grade(p);
    assertEquals(p, grade.getPoints());
}

Upvotes: 3

Related Questions