2016-01-26 51 views
0

的測試方法具有以下代碼返回null java.lang.reflect.Method中:getAnnotation(<T>類)總是當我使用了EasyMock/PowerMock嘲笑java.lang.reflect.Method中

Method method= PowerMock.createMock(Method.class); 
SuppressWarnings sw = EasyMock.createMock(SuppressWarnings.class); 
EasyMock.expect(method.getAnnotation(SuppressWarnings.class)).andReturn(sw); 

在被測試的方法,
method.getAnnotation(SuppressWarnings.class);總是返回null。

我不知道爲什麼。有人能幫助我嗎?

//code: 
@Retention(RetentionPolicy.RUNTIME) 
@Target(ElementType.METHOD) 
public @interface Anonymous { 

} 

public class AnnotationClass { 
    public Anonymous fun(Method m){ 
     Anonymous anonymous = m.getAnnotation(Anonymous.class); 
     return anonymous; 
    } 
} 

// test class: 
@RunWith(PowerMockRunner.class) 
@PrepareForTest(Method.class) 
public class AnnotationClassTest { 
    @Test 
    public void test() throws NoSuchMethodException, SecurityException { 
     AnnotationClass testClass = new AnnotationClass(); 
     final Method mockMethod = PowerMock.createMock(Method.class); 
     final Anonymous mockAnot = EasyMock.createMock(Anonymous.class); 

     EasyMock.expect(mockMethod.getAnnotation(Anonymous.class)).andReturn(mockAnot); 
     PowerMock.replay(mockMethod); 

     final Anonymous act = testClass.fun(mockMethod); 
     Assert.assertEquals(mockAnot, act); 

     PowerMock.verify(mockMethod); 
    } 
} 

error: 
java.lang.AssertionError: expected:<EasyMock for interface 
com.unittest.easymock.start.Anonymous> but was:<null> 

回答

0

SuppressWarnings具有@Retention(value=SOURCE)這意味着它不提供在運行時:

public static final RetentionPolicy SOURCE:註釋是由編譯器被丟棄。

但是,如果你會用不同的註釋,在運行時可嘗試你的代碼,method.getAnnotation(MyAnnotation.class)仍然會返回null。也就是說,因爲默認情況下,模擬的Method將返回方法調用null

我覺得你的問題是在模擬的配置,當我運行的代碼(使用一個註解,可在運行時)我得到以下異常:

Exception in thread "main" java.lang.IllegalStateException: no last call on a mock available 
at org.easymock.EasyMock.getControlForLastCall(EasyMock.java:466) 
at org.easymock.EasyMock.expect(EasyMock.java:444) 
at MockStuff.main(MockStuff.java:54) 

This page在如何一些解釋嘲笑最後一堂課(如Method)。


你的代碼給我完全一樣的結果。我能得到它的工作使用下面的代碼:

@RunWith(PowerMockRunner.class) 
@PrepareForTest(Method.class) 
public class AnnotationClassTest { 
    @Test 
    public void test() throws NoSuchMethodException, SecurityException { 
    final Method mockMethod = PowerMock.createMock(Method.class); 
    final Anot mockAnot = EasyMock.createMock(Anot.class); 

    EasyMock.expect(mockMethod.getAnnotation(Anot.class)).andReturn(mockAnot); 
    PowerMock.replay(mockMethod); 

    final Anot methodReturn = mockMethod.getAnnotation(Anot.class); 
    Assert.assertEquals(mockAnot, methodReturn); 
    } 
} 

@Retention(RetentionPolicy.RUNTIME) 
@interface Anot {} 

注意,這個代碼是自包含的,我定義的Anot接口,因爲你沒有給Anonymous定義。

+0

當我使用具有@Retention(RetentionPolicy.RUNTIME)的自定義註釋時,我得到了相同的結果 – niaomingjian

+0

您是對的,我更新了我的答案。 – rinde

+0

我再次嘗試,但仍然失敗。我在頁面中輸入了源代碼。您能幫我解決這個問題嗎?謝謝。 – niaomingjian