Created
October 15, 2011 02:44
-
-
Save takezoe/1288931 to your computer and use it in GitHub Desktop.
Guava 10で導入されたOptionalを試してみる
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package jp.sf.amateras.guava; | |
import static junit.framework.Assert.*; | |
import org.junit.Test; | |
import com.google.common.base.Optional; | |
public class OptionalTest { | |
@Test | |
public void testOf(){ | |
// ofにはnullは渡せない | |
Optional<String> optional = Optional.of("test"); | |
assertTrue(optional.isPresent()); | |
assertEquals("test", optional.get()); | |
} | |
@Test | |
public void testFromNullable1(){ | |
// nullの可能性がある場合はfromNullableを使用する | |
Optional<String> optional = Optional.fromNullable("test"); | |
assertTrue(optional.isPresent()); | |
assertEquals("test", optional.get()); | |
} | |
@Test | |
public void testFromNullable2(){ | |
// nullの可能性がある場合はorNull()で値を取得する | |
Optional<String> optional = Optional.fromNullable(null); | |
assertFalse(optional.isPresent()); | |
assertNull(optional.orNull()); | |
} | |
@Test | |
public void testAbsent(){ | |
// absentはnullの場合と同じ | |
Optional<String> optional = Optional.absent(); | |
assertFalse(optional.isPresent()); | |
assertNull(optional.orNull()); | |
} | |
@Test | |
public void testOr(){ | |
// orはnullの場合に指定した値を返却する | |
Optional<String> optional = Optional.absent(); | |
assertFalse(optional.isPresent()); | |
assertEquals("test", optional.or("test")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment