public class ValidationCodeEvent {
private String code;
public ValidationCodeEvent(String code) {
this.code = code;
}
public String getCode() {
return code;
}
}
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.SmallTest;
import com.pickupnow.customer.broadcast_receivers.SmsCodeBroadcastReceiver;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(AndroidJUnit4.class)
@SmallTest
public class SmsCodeValidatorTests {
@Test
public void parseSmsCodes() {
String code = SmsCodeBroadcastReceiver.manageSmsBody("This is a code 123123 and it should work");
assertThat(code).isEqualTo("123123");
}
@Test
public void noCodeReturnsNull() {
String code = SmsCodeBroadcastReceiver.manageSmsBody("There is no code so should return null");
assertThat(code).isNull();
}
@Test
public void emptyBodyReturnsNull() {
String code = SmsCodeBroadcastReceiver.manageSmsBody(null);
assertThat(code).isNull();
}
}
public class SmsCodeBroadcastReceiver extends BroadcastReceiver {
public static IntentFilter getFilter() {
IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
return filter;
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Telephony.Sms.Intents.SMS_RECEIVED_ACTION)) {
SmsMessage[] messages = getMessagesFromIntent(intent);
for (SmsMessage message : messages) {
String msgBody = message.getMessageBody();
manageSmsBody(msgBody);
}
}
}
@VisibleForTesting
@Nullable
public static String manageSmsBody(String body) {
String code = getDigits(body);
if (code != null) {
BusHelper.post(new ValidationCodeEvent(code));
}
return code;
}
/**
* Returns a string just with digits or null if there are no digits.
*/
@Nullable
public static String getDigits(String content) {
if (content == null) {
return null;
}
String code = content.replaceAll("\\D+", "");
if (code.matches("\\d+")) {
return code;
} else {
return null;
}
}
}