1 package test.inject;
2 
3 import org.testng.Assert;
4 import org.testng.ITestResult;
5 import org.testng.SkipException;
6 import org.testng.annotations.AfterMethod;
7 import org.testng.annotations.BeforeClass;
8 import org.testng.annotations.BeforeMethod;
9 import org.testng.annotations.Test;
10 
11 import java.lang.reflect.Method;
12 
13 public class InjectBeforeAndAfterMethodsWithTestResultSampleTest {
14   static int m_success;
15   private ITestResult m_testResult;
16 
17   @Test
pass()18   public void pass() {
19     Assert.assertEquals(m_testResult.getAttribute("before"), 10);
20   }
21 
22   @Test
fail()23   public void fail() {
24     throw new RuntimeException();
25   }
26 
27   @Test
skip()28   public void skip() {
29     throw new SkipException("Skipped");
30   }
31 
32   @BeforeClass
init()33   public void init() {
34     m_success = 3;
35   }
36 
37   @BeforeMethod
before(Method m, ITestResult r)38   public void before(Method m, ITestResult r) {
39     m_testResult = r;
40     r.setAttribute("before", 10);
41   }
42 
43   @AfterMethod
after(Method m, ITestResult r)44   public void after(Method m, ITestResult r) {
45     String name = m.getName();
46     Assert.assertEquals(r, m_testResult);
47     if (("pass".equals(name) && r.getStatus() == ITestResult.SUCCESS)
48         || ("fail".equals(name) && r.getStatus() == ITestResult.FAILURE)
49         || ("skip".equals(name) && r.getStatus() == ITestResult.SKIP)) {
50           m_success--;
51         }
52   }
53 }
54