Java JUnit框架@BeforeClass和(Power)Mockito用于静态方法

时间:2013-12-20 08:18:29

标签: java junit powermock

我有以下测试类:

@RunWith(PowerMockRunner.class)
@PrepareForTest(Foo.class)
public class MyTestClass {

  @BeforeClass
  public static void setUpBeforeClass() {
    // class Foo: singleton pattern
    Foo mockFoo = Mockito.mock(Foo.class);
    when(mockFoo.theMethod()).thenReturn(...);
    PowerMockito.mockStatic(Foo.class);
    PowerMockito.when(Foo.getInstance()).thenReturn(mockFoo);
  }

  @Before
  public void setUp() {
  }

  @After
  public void tearDown() {
  }

  @AfterClass
  public static void tearDownAfterClass() {
  }

  // MyClass.myStaticMethod() calls to some point Foo.getInstance().theMethod()

  // when the MyTestClass in executed as JUnit in Eclipse this test passes
  // when this test 
  @Test
  public void test1() {
    MyClass.myStaticMethod(myargs);
  }

  // when the MyTestClass in executed as JUnit in Eclipse this test fails because Foo.getInstance() returns null
  // but this test passes if it is executed standalone (test2() selected and run as JUnit test in Eclipse)
  @Test
  public void test2() {
    MyClass.myStaticMethod(myargs);
  }

  // when the MyTestClass in executed as JUnit in Eclipse this test fails because Foo.getInstance() returns null
  // but this test passes if it is executed standalone  (test3() selected and run as JUnit test in Eclipse)
  @Test
  public void test3() {
    MyClass.myStaticMethod(myargs);
  }
}

我知道setUpBeforeClass()在第一次测试之前只运行一次,我知道框架JUnit为每次测试运行创建一个新的MyTestClass实例。但我无法理解为什么当我作为JUnit执行时,只有第一个测试通过,而每个测试都以独立的方式运行它们作为JUnit。 你能告诉我为什么吗?为什么嘲笑只能在第一次执行的测试中“存活”? 如果setUpBeforeClass()中的代码不在setUpBeforeClass()中,而是在每次测试之前执行的setUp()中,那么当我以JUnit的形式执行该类时,所有测试都会通过。

0 个答案:

没有答案