美文网首页
<翻译>使用Junit Rules简化你的测试用例

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

作者: ShootHzj | 来源:发表于2017-09-07 00:23 被阅读54次

翻译自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
  }
}

相关文章

网友评论

      本文标题:<翻译>使用Junit Rules简化你的测试用例

      本文链接:https://www.haomeiwen.com/subject/rbdbjxtx.html