2014-08-31 11 views
10

Tôi đang cố gắng thử phương pháp tĩnh riêng tư anotherMethod(). Xem mã bên dướiLàm thế nào tôi có thể thử phương pháp tĩnh riêng với PowerMockito?

public class Util { 
    public static String method(){ 
     return anotherMethod(); 
    } 

    private static String anotherMethod() { 
     throw new RuntimeException(); // logic was replaced with exception. 
    } 
} 

Đây là tôi mã kiểm tra

@PrepareForTest(Util.class) 
public class UtilTest extends PowerMockTestCase { 

     @Test 
     public void should_prevent_invoking_of_private_method_but_return_result_of_it() throws Exception { 

      PowerMockito.mockStatic(Util.class); 
      PowerMockito.when(Util.class, "anotherMethod").thenReturn("abc"); 

      String retrieved = Util.method(); 

      assertNotNull(retrieved); 
      assertEquals(retrieved, "abc"); 
     }  
} 

Nhưng mỗi ngói tôi chạy nó tôi nhận được ngoại lệ này

java.lang.AssertionError: expected object to not be null 

Tôi cho rằng tôi đang làm một cái gì đó sai trái với chế giễu đồ đạc. Bất kỳ ý tưởng làm thế nào tôi có thể sửa chữa nó?

Trả lời

23

Để thực hiện điều này, bạn có thể sử dụng PowerMockito.spy(...)PowerMockito.doReturn(...). Hơn nữa, bạn phải xác định Á hậu PowerMock tại lớp thử nghiệm của bạn, như sau:

@PrepareForTest(Util.class) 
@RunWith(PowerMockRunner.class) 
public class UtilTest { 

    @Test 
    public void testMethod() throws Exception { 
     PowerMockito.spy(Util.class); 
     PowerMockito.doReturn("abc").when(Util.class, "anotherMethod"); 

     String retrieved = Util.method(); 

     Assert.assertNotNull(retrieved); 
     Assert.assertEquals(retrieved, "abc"); 
    } 
} 

Hy vọng nó sẽ giúp bạn.

-1

Tôi không chắc chắn những gì phiên bản của PowerMock bạn đang sử dụng, nhưng với những phiên bản sau này, bạn nên sử dụng @RunWith(PowerMockRunner.class) @PrepareForTest(Util.class)

Nói này, tôi tìm thấy bằng PowerMock để được thực sự có vấn đề và một dấu hiệu chắc chắn của một người nghèo thiết kế. Nếu bạn có thời gian/cơ hội để thay đổi thiết kế, tôi sẽ cố gắng và làm điều đó trước.

+0

số cho 'TestNG' tôi cần sử dụng các chú thích của tôi. – Aaron

4

Nếu anotherMethod() mất bất kỳ một lý lẽ gì anotherMethod (parameter), invocation đúng của phương pháp này sẽ là:

PowerMockito.doReturn("abc").when(Util.class, "anotherMethod", parameter); 
Các vấn đề liên quan