목차

JUnit Rules

Exception Rule

  @Rule
  public ExpectedException exception = ExpectedException.none();
 
  @Test
  public void throwsIllegalArgumentExceptionIfIconIsNull() {
    // 발생할 예외에 대한 조건 기술
    exception.expect(IllegalArgumentException.class);
    exception.expectMessage("Negative value not allowed");
 
    ClassToBeTested t = new ClassToBeTested();
    t.methodToBeTest(-1);
  }

임시 폴더 Rule

  @Rule
  public TemporaryFolder folder = new TemporaryFolder();
 
  // ...
 
  File createdFolder = folder.newFolder("newfolder");
  File createdFile = folder.newFile("myfilefile.txt");  

External Resource Rule

public static class UsesExternalResource {
  Server myServer = new Server();
 
  @Rule
  public ExternalResource resource = new ExternalResource() {
    @Override
    protected void before() throws Throwable {
      myServer.connect();
    };
 
    @Override
    protected void after() {
      myServer.disconnect();
    };
  };
 
  @Test
  public void testFoo() {
    new Client().run(myServer);
  }
}

System Rules