简体   繁体   中英

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 ? 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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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