查看链接

@Before

在当前测试类中,使用@Before注解的方法会在后面的每一个测试Test前运行,这将简化很多重复代码的编写。

在每一个测试之前都需要先搭建网络(setup()),正如示例代码所示:

@Before
public void setup() {
    network = new MockNetwork(new MockNetworkParameters().withCordappsForAllNodes(ImmutableList.of(
            TestCordapp.findCordapp("com.example.contract"),
            TestCordapp.findCordapp("com.example.flow"))));
    a = network.createPartyNode(null);
    b = network.createPartyNode(null);
    // For real nodes this happens automatically, but we have to manually register the flow for tests.
    for (StartedMockNode node : ImmutableList.of(a, b)) {
        node.registerInitiatedFlow(ExampleFlow.Acceptor.class);
    }
    network.runNetwork();
}

@After

在当前测试类中,使用@After注解的方法会在后面的每一个测试Test后运行,比如测试完成后需要停止节点,关闭网络(tearDown())。

@After
public void tearDown() {
    network.stopNodes();
}

Rule

@Rule注解是方法级别的,每个测试方法执行时都会执行被@Rule注解的成员变量的方法(类似于@Before)。

这相当于给每个测试方法定义一个规则,比如示例:

@Rule
public final ExpectedException exception = ExpectedException.none();

可以这么理解:

rule为:如果抛出异常,则抛出异常为ExpectedException.none()

这规则是可以自定义的,可以参考这个链接

@Before注解的方法只能作用于当前测试类及其子类,而实现了TestRule的类可以被用于多个测试类

@ClassRule注解是类级别的,测试类执行时仅会执行一次被@ClassRule注解的静态变量的方法(类似于@BeforeClass)。