user4424557
user4424557

Reputation:

How can I JUnit test a model within Android?

Below I have an example of a model I have created within Android Studio to be utilised within my application.

Could someone with experience in this area, offer me examples of unit tests I could carry out on this model (in android) to get me started?

- I'm referring to JUnit Testing via Google Android Testing

Creating functions to JUnit test utilising(extending) TestCases (junit.framework) etc

code for Contact model:

public class Contact extends MainModel
{
    private Long id;
    private String personName;
    private String phoneNumber;
    private String occupation;



    public Long getId() 
    { 
        return id; 
    }

    public void setId(Long id)
    { 
        this.id = id; 
    }



    public String getPersonName() 
    { 
        return personName; 
    }

    public void setPersonName(String personName) 
    { 
        this.personName = personName; 
    }



    public String getPhoneNumber()
    { 
        return phoneNumber; 
    }

    public void setPhoneNumber(String phoneNumber) 
    { 
        this.phoneNumber = phoneNumber; 
    }



    public String getOccupation()
    {
        return occupation;
    }

    public void setOccupation(String occupation)
    {
        this.occupation = occupation;
    }

}

Upvotes: 2

Views: 2426

Answers (2)

user4423103
user4423103

Reputation:

Been looking into similar junit tests in Android lately, this should defiantly get you started. It should explain how to test the getting and setting

public class SurveyTest extends TestCase {

private Survey survey;

protected void setUp() throws Exception {
    super.setUp();  
    survey = new Survey();
}

public void testSurvey() {
    survey.toString();
}

public void testSurveyLongString() {
    fail("Not yet implemented");
}

public void testGetId() {
    long expected = (long) Math.random();
    survey.setId(expected);
    long actual = survey.getId();
    Assert.assertEquals(expected, actual);
}

public void testGetTitle() {
    String expected = "surveytitle";
    survey.setTitle(expected);
    String actual = survey.getTitle();
    Assert.assertEquals(expected, actual);  
}

public void testIsActive() {
    Boolean expected = true;
    survey.setActive(expected);
    Boolean actual = survey.isActive();
    Assert.assertEquals(expected, actual);
}

public void testGetQuestions() {
    fail("Not yet implemented");
}

}

Upvotes: 7

GreyBeardedGeek
GreyBeardedGeek

Reputation: 30088

The only reasonable way that I've found to write unit tests for classes that don't depend on the Android libraries (Activities, Context, etc.) is to install Robolectric.

Then, since Robolectric is based on JUnit, in addition to Robolectric tests, which do typically involve Context and friends, you have the infrastructure in place to support simple, non-Android JUnit tests.

Upvotes: 0

Related Questions