简体   繁体   English

Android JUnit测试-测试活动中的方法

[英]Android JUnit Testing - Test a method in an activity

I receive a string from a server in the main activity .I have to write a test case for that (whether the string is received in the correct format) How do I write a test case for methods in android ? 我在主要活动中从服务器接收到一个字符串。我必须为此编写一个测试用例(是否以正确的格式接收到该字符串)如何为android中的方法编写一个测试用例? I am completely new to Testing and any resources are greatly helpful 我对测试完全陌生,任何资源都对您有很大帮助

As you don't want to test the Activity but rather the business logic, you could factor out the receiving of the String to an own class and test this class instead in an isolated way where you don't have any Android specifics around. 由于您不想测试Activity而是要测试业务逻辑,因此可以将String的接收分解为一个自己的类,并以一种孤立的方式测试该类,因为您没有周围的Android细节。 For example, you could write a POJO class ServerValidator which receives a String and returns a boolean value and you use this validator in your activity and can test it without needing any Android surroundings. 例如,您可以编写一个POJO类ServerValidator ,该类接收一个String并返回一个布尔值,并且您可以在活动中使用此验证器,并且可以在不需要任何Android环境的情况下对其进行测试。

public class ServerValidator {

    public static boolean validate(String input) {
        return ...; // Insert validation logic
    }
}

public class ServerValidatorTest {

    @Test
    public void testValidateFailure() {
        final String faultyString = ...;
        Assert.assertFalse(ServerValidator.validate(faultyString));
    }

    @Test
    public void testValidateSuccessful() {
        final String correctString = ...;
        Assert.assertTrue(ServerValidator.validate(correctString));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM