我如何在Android中测试JUnit模型?

时间:2015-01-23 15:46:23

标签: java android unit-testing android-activity

下面我有一个我在Android Studio中创建的模型示例,可以在我的应用程序中使用。

在这个领域有经验的人能为我提供一些单元测试的例子,我可以在这个模型上(在android中)让我开始吗?

- 我指的是通过Google Android测试进行的JUnit测试

使用(扩展)TestCases(junit.framework)等创建函数到JUnit测试

代码联系模型:

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;
    }

}

2 个答案:

答案 0 :(得分:4)

最近在Android中进行类似的junit测试,这应该会让你开始。它应该解释如何测试获取和设置

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");
}

}

答案 1 :(得分:0)

我发现为不依赖于Android库(活动,上下文等)的类编写单元测试的唯一合理方法是安装Robolectric。

然后,由于Robolectric基于JUnit,除了通常涉及Context和朋友的Robolectric测试之外,您还拥有基础设施来支持简单的非Android JUnit测试。