<翻译>使用Junit Rules简化你的测试用例

翻译自https://carlosbecker.com/posts/junit-rules/
我们从一个简单的例子开始,假设你想要为类中所有的测试方法设置时延。简单的方法就是这样:

public class BlahTest {
  
  @Test(timeout = 1000)
  public void testA() throws Exception {
    //...
  }
  
  @Test(timeout = 1000)
  public void testB() throws Exception {
  }
  
  @Test(timeout = 1000)
  public void testC() throws Exception {
  }
  
  @Test(timeout = 1000)
  public void testD() throws Exception {
  }
  
  @Test(timeout = 1000)
  public void testE() throws Exception {
  }
}

这样子,你重复了很多次,如果你想要改变这个延迟,你需要在所有方法里面更改这个数字。使用Timeout Rule即可

public class BlashTest {
  @Rule
  public Timeout timeout = new Timeout(2000);
  
  @Test
  public void testA() throws Exception {
  }
  
  @Test
  public void testB() throws Exception {
  }
  
  @Test
  public void testC() throws Exception {
  }

  @Test
  public void testD() throws Exception {
  }
}

临时文件夹

public class BlahTest {
  @Rule
  public TemporaryFolder tempFolder = new TemporaryFolder();
  
  @Test
  public void testIcon() throws Exception {
    File icon = tempFolder.newFile("icon.png");
  }
 }

期望中的异常

public class BlahTest {
  @Rule
  public ExpectedException exception = ExpectedException.none();

  @Test
  public void testIcon() throws Exception {
    exception.expect(IllegalArgumentException.class);
    exception.expectMessage("Dude, this is invalid");
  }
}

你也可以自己实现TestRule接口,举个例子,初始化Mockito mocks的 Rule

@RequiredArgsConstructor
public class MockRule implements TestRule {
  private final Object target;
  
  public Statement apply(Statement base, Description description) {
    return new Statement() {
      @Override
      public void evaluate() throws Throwable {
        MockitoAnnotations.initMocks(target);
        base.evaluate();
      }
    };
  }
}

使用它,在你的类中声明

public class BlahTest {
  @Rule
  public MockRule mock = new MockRule(this);
  
  @Mock
  private BlahService service;

  @Test
  public void testBlash() throws Exception {
    Assert.assertThat(service.blah(), CoreMatchers.notNullValue());
  }
}

使用ClassRule的例子

public class MyServer extends ExternalResource {
  @Override
  protected void before() throws Throwable {
    //start the server
  }
  
  @Override
  public void after() {
    //stop the server
  }
}

使用ClassRule注册的时候,你的rule实例应该为静态。

public class BlahServerTest {
  @ClassRule
  public static MyServer server = new MyServer();
  
  @Test
  public void testBlah() throws Exception {
    //test sth that depends on the server
  }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容