EditTextTest.java revision b47b1af9719958cb4fdb21eac8a8bde035c2c574
1package com.xtremelabs.robolectric.shadows; 2 3import static org.hamcrest.CoreMatchers.equalTo; 4import static org.junit.Assert.assertThat; 5import static org.junit.Assert.assertTrue; 6import static org.mockito.Matchers.any; 7import static org.mockito.Matchers.anyInt; 8import static org.mockito.Matchers.eq; 9import static org.mockito.Mockito.mock; 10import static org.mockito.Mockito.when; 11 12import java.util.Random; 13 14import org.junit.Test; 15import org.junit.runner.RunWith; 16 17import android.util.AttributeSet; 18import android.widget.EditText; 19 20import com.xtremelabs.robolectric.WithTestDefaultsRunner; 21 22@RunWith(WithTestDefaultsRunner.class) 23public class EditTextTest { 24 25 @Test 26 public void shouldBeFocusableByDefault() throws Exception { 27 assertTrue(new EditText(null).isFocusable()); 28 assertTrue(new EditText(null).isFocusableInTouchMode()); 29 } 30 31 @Test 32 public void givenInitializingWithAttributeSet_whenMaxLengthDefined_thenRestrictTextLengthToMaxLength() { 33 int maxLength = anyInteger(); 34 AttributeSet attrs = attributeSetWithMaxLength(maxLength); 35 EditText editText = new EditText(null, attrs); 36 String excessiveInput = stringOfLength(maxLength * 2); 37 38 editText.setText(excessiveInput); 39 40 assertThat(editText.getText().toString(), equalTo(excessiveInput.subSequence(0, maxLength))); 41 } 42 43 @Test 44 public void givenInitializingWithAttributeSet_whenMaxLengthNotDefined_thenTextLengthShouldHaveNoRestrictions() { 45 AttributeSet attrs = attributeSetWithoutMaxLength(); 46 EditText editText = new EditText(null, attrs); 47 String input = anyString(); 48 49 editText.setText(input); 50 51 assertThat(editText.getText().toString(), equalTo(input)); 52 } 53 54 @Test 55 public void whenInitializingWithoutAttributeSet_thenTextLengthShouldHaveNoRestrictions() { 56 EditText editText = new EditText(null); 57 String input = anyString(); 58 59 editText.setText(input); 60 61 assertThat(editText.getText().toString(), equalTo(input)); 62 } 63 64 private String anyString() { 65 return stringOfLength(anyInteger()); 66 } 67 68 private String stringOfLength(int length) { 69 StringBuilder stringBuilder = new StringBuilder(); 70 71 for (int i = 0; i < length; i++) 72 stringBuilder.append('x'); 73 74 return stringBuilder.toString(); 75 } 76 77 private int anyInteger() { 78 return new Random().nextInt(1000) + 1; 79 } 80 81 private AttributeSet attributeSetWithMaxLength(int maxLength) { 82 AttributeSet attrs = mock(AttributeSet.class); 83 when(attrs.getAttributeIntValue(eq("android"), eq("maxLength"), anyInt())).thenReturn(maxLength); 84 return attrs; 85 } 86 87 private AttributeSet attributeSetWithoutMaxLength() { 88 AttributeSet attrs = mock(AttributeSet.class); 89 when(attrs.getAttributeIntValue("android", "maxLength", Integer.MAX_VALUE)).thenReturn(Integer.MAX_VALUE); 90 return attrs; 91 } 92} 93