无法使用AndroidAnnotation,Robolectric和PowerMock进行测试

时间:2016-10-27 10:47:29

标签: robolectric powermock android-annotations

我是单元测试的新手,我正在尝试使用robolectric为我的Android应用程序做测试,但我遇到了一些问题

DemoPresenterTest

@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 23)
@PowerMockIgnore({ "org.mockito.*", "org.robolectric.*", "android.*" })
@PrepareForTest(DemoPresenterImpl_.class)
public class DemoPresenterTest {

    @Rule
    public MockitoRule rule = MockitoJUnit.rule();

    private MockDemoNetworkService mMockDemoNetworkService;
    private MockLceView mLceView;

    private DemoPresenterImpl_ mPresenter;

    @Before
    public void setup() {

        mMockDemoNetworkService = Mockito.mock(MockDemoNetworkService.class);
        mLceView = Mockito.mock(MockLceView.class);
        PowerMockito.mockStatic(DemoPresenterImpl_.class);

        mPresenter = DemoPresenterImpl_.getInstance_(RuntimeEnvironment.application);

        mPresenter.service = mMockDemoNetworkService;
        mPresenter.view = mLceView;
    }

    @Test
    public void testDownloadData() {

        mPresenter.downloadData();
        Mockito.verify(mLceView).onError(Mockito.anyInt());
    }
}

DemoPresenterImpl

@EBean
public class DemoPresenterImpl implements DemoPresenter {

    @Bean(DemoNetworkService.class)
    DemoService service;

    protected LceView<Demo> view;

    /**
     * download the data from server for the first time, data will be saved into the database
     * and for the next time it will query the database instead
     */
    @Override
    @Background(delay = 1000)
    public void downloadData() {

        try {

            List<Demo> result = service.getDemoList();

            if (result != null) {
                view.setData(result);
            } // add else if the result is not return empty list but null

        } catch (NetworkFailException e) {
            view.onError(e.getResponse().getCode());
        }
    }

    @Override
    public void attach(LceView<Demo> view) {
        this.view = view;
    }
}

MockDemoNetworkService

public class MockDemoNetworkService implements DemoService {

    @Override
    public List<Demo> getDemoList() throws NetworkFailException {

        NetworkFailResponse response = new NetworkFailResponse();
        response.setCode(500);

        throw new NetworkFailException(response);
    }

    @Override
    public boolean setDemoList(List<Demo> demoList) {
        return false;
    }
}

当我运行测试时,它返回“不能继承最终类类com。*。DemoPresenterImpl_”,如果我改为DemoPresenterImpl,测试可以运行但是mLceView永远不会被调用

  

想要但未被调用:mockLceView.onError();    - &GT;在org.robolectric.RobolectricTestRunner $ 2.evaluate(RobolectricTestRunner.java:245)   实际上,这个模拟没有互动。

我做错了吗?

1 个答案:

答案 0 :(得分:0)

我认为你可以删除@PrepareForTest,因为你没有嘲笑演示者,你实际上正在测试它。然后你应该使用DemoPresenterImpl_,因为它包含所需的生成代码。