Skip to content

Instantly share code, notes, and snippets.

@takezoe
Created October 15, 2011 02:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takezoe/1288931 to your computer and use it in GitHub Desktop.
Save takezoe/1288931 to your computer and use it in GitHub Desktop.
Guava 10で導入されたOptionalを試してみる
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