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

Fail to run test with AndroidAnnotation, Robolectric and PowerMock

我是单元测试的新手,我正在尝试使用 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;
    }
}

当我运行测试它时returns"Cannot subclass final class class com.*.DemoPresenterImpl_",如果我换成DemoPresenterImpl,测试可以运行但是mLceView永远不会被调用

Wanted but not invoked: mockLceView.onError(); -> at org.robolectric.RobolectricTestRunner.evaluate(RobolectricTestRunner.java:245) Actually, there were zero interactions with this mock.

我是不是做错了什么?

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