user2957741
user2957741

Reputation: 1083

junit test case with null object

I want to write Person class with 3 parameter constructor and if user give null string for name and surname for a person, I want to return null for that object because I want to use junit assertNull function to show that object is not created with null string.

public Person(String names,String surnames,int ages)
{
    if(!names.equals(null) && !surnames.equals(null))
    {
        name = names;
        surname = surnames;
    }
    else
    {
        return;
    }

    if(ages > 0)
        age = ages;
    else
        return;
}

and test is like that

    @Test
public void createPerson()
{
    String ad = null;
    String soyad = null;
    int age = 10;
    Person p = new Person(ad, soyad, age);
    assertNull("Object is not created!", p );
}

how can do it I get null pointer exception?

Upvotes: 0

Views: 12338

Answers (1)

Roland
Roland

Reputation: 1240

You get a NullPointerException because you are calling the equals method on a null object. If you want to check whether a String is not null, you need to use someString != null.

What you need to do is:

if (names != null && surnames != null)

But that does not solve your problem that it is not possible to return null from a constructor. The only thing you could do ist to throw a NullPointerException—and that is exactly what your code does. There must be some other way to solve the problem you have.

Upvotes: 1

Related Questions