2016-03-02 52 views
1

這是CustomAdapter不工作(順便說一句:真的老代碼,應該有一天提高):EasyMock的與Robolectric:EasyMock的預期

public class CustomAdapter extends BaseAdapter{ 

    private SortedSet<Integer> mHiddenItems = new TreeSet<>();  

    @Override 
    public final int getCount(){ 
     return mHiddenItems.size(); 
    } 

    ... 
} 

這是我的測試類CustomAdapterTest(以及一切正常這裏) :

public class CustomAdapterTest extends TestCase{ 

    private static final int ITEMS_IN_ADAPTER = 10; 
    private CustomAdapter mCustomAdapter; 

    @Override 
    public void setUp() throws Exception{ 
     super.setUp(); 

     mCustomAdapter = EasyMock.createMockBuilder(CustomAdapter.class) 
      .addMockedMethod("method1") 
      .addMockedMethod("method2") 
      .createMock(); 

     expect(mCustomAdapter.method2()).andReturn(ITEMS_IN_ADAPTER).anyTimes(); 
    } 

    public void testOne(){ 
     EasyMock.replay(mCustomAdapter); 
     assertEquals(ITEMS_IN_ADAPTER,mCustomAdapter.getTotalCount()); 
     ..... 
    } 

    ...... 

} 

嘗試使用Robolectric,並解決了一個錯誤之後,這是CustomAdapterTest的樣子:

@RunWith(RoboelectricGradleTestRunner.class) 
@Config(constants = BuildConfig.class , packageName="my.package.name") 
public class CustomAdapterTest{ 

    private static final int ITEMS_IN_ADAPTER = 10; 
    private CustomAdapter mCustomAdapter; 

    @Before 
    public void setUp(){ 
     System.setProperty("dexmaker.dexcache",RuntimeEnvironment.application.getCacheDir().getPath()) 

     mCustomAdapter = EasyMock.createMockBuilder(CustomAdapter.class) 
      .addMockedMethod("method1") 
      .addMockedMethod("method2") 
      .createMock(); 

     expect(mCustomAdapter.method2()).andReturn(ITEMS_IN_ADAPTER).anyTimes(); 
    } 

    public void testOne(){ 
     EasyMock.replay(mCustomAdapter); 
     assertEquals(ITEMS_IN_ADAPTER,mCustomAdapter.getTotalCount()); 
     ..... 
    } 

    ...... 

} 

當我使用Robolectric運行CustomAdapterTest#testOne()時,我不知道爲什麼,但mCustomAdapter.mHiddenItems爲null,因此在調用mCustomAdapter.getCount()時導致NPE。這不會發生在CustomAdapterTest的第一個版本上。

1)爲什麼使用RobolectricGradleTestRunner private SortedSet mHiddenItems = new TreeSet<>();未執行?

2)如何解決這個問題?我希望它按預期執行private SortedSet mHiddenItems = new TreeSet<>();

回答

0

這不是您的問題的確切答案。但我只會重新測試測試和班級。

我會刪除部分模仿和注入項目在構造函數或通過設置。或者我會在構造函數中再次模擬物品提供者。

+0

這不是一個有效的解決方案(可能是其他情況下),但謝謝,我感謝你在我的問題上的努力。 – JoseF