2017-04-19 23 views
2

我爲下面的代碼編寫單元測試,即使我嘲笑字段,即時獲取NPE,我該如何解決這個問題。這些領域都存在與@Inject註解如何在單元測試時使用NPE for @Inject字段?

@Component 
interface A { 
    void run(); 
} 

class B { 
    @Inject 
    A a; 

    void someMethod() { 
     a.run(); 
    }} 

class C{ 
    @Inject 
    B b; 

    void anotherMethod() { 
     b.someMethod(); 
    } 
} 

class CTest { 
    @Mock 
    B b; 
    // remains null when invoked in the actual class though its mocked instance is 
    // present here 

    @Mock 
    A a; 
    //// remains null when invoked in the actual class though its mocked instance 
    //// is present here 

    @InjectMocks 
    C c; 

    @Before 
    public void initialize() { 
     MockitoAnnotations.initMocks(this); 
    } 

    @Test 
    public void test() { 
     c.anotherMethod(); 
    } 

} 

所以,我怎麼能得到其中場被注射使用的Mockito @Inject在實際的類嘲笑價值?

回答

1

我的猜測是你應該用@RunWith(MockitoJUnitRunner.class)註釋你的CTest類,並刪除你之前的方法,因爲它會變得不必要的(@RunWith會做注入模擬的技巧)。

UPDATE

其實我跑你的代碼在我的IDE。一切都很好,沒有NPE。可能你必須檢查你的進口是否正確。這裏是我與你進行比較:

import org.junit.Before; 
import org.junit.Test; 
import org.mockito.InjectMocks; 
import org.mockito.Mock; 
import org.mockito.MockitoAnnotations; 
import javax.inject.Inject; 
import org.springframework.stereotype.Component; 

此外,請支付您使用大寫字母聲明Class C注意(應該是class C)在你的問題,所以這個非常的代碼將無法編譯。

+0

嘿謝謝你的答案,這段代碼只是例子而不是我的實際代碼。它建議使用@RunWith(MockitoJUnitRunner.class)或MockitoAnnotations.initMocks(this) - 參考http://stackoverflow.com/a/28969255/2340345 – user2340345

相關問題