有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在公共方法中提供对象,以使用PowerMock访问其中的另一个方法?

我正在为一个类编写单元测试用例

public class CurrentMoreInfoDataProvider implements CurrentMoreInfoInterface.presenterToModel{

private CurrentMoreInfoInterface.modelToPresenter modelToPresenter;

public CurrentMoreInfoDataProvider(CurrentMoreInfoInterface.modelToPresenter modelToPresenter) {
    this.modelToPresenter = modelToPresenter;
}

@Override
public void provideData() {
    WeatherApiResponsePojo apiWeatherData = WeatherDataSingleton.getInstance().getApiWeatherData();
    if(null != apiWeatherData.getCurrently()){
        CurrentlyPojo currently = apiWeatherData.getCurrently();
        if(null != currently){
            populateWeatherData(currently);
        }
    }
}

public void populateWeatherData(CurrentlyPojo currently) {....}

我只想使用power mock的verify方法来测试populateWeatherData是否得到执行。下面是到目前为止我的测试用例

@RunWith(PowerMockRunner.class)
@PrepareForTest(CurrentMoreInfoDataProvider.class)
public class TestCurrentMoreInfoDataProvider {

    private CurrentMoreInfoDataProvider dataProvider;
    @Mock
    CurrentMoreInfoInterface.modelToPresenter modelToPresenter;

    private CurrentlyPojo currentlyPojo = new CurrentlyPojo();
    @Test
    public void testPopulateWeatherData(){

        dataProvider = PowerMockito.spy(new CurrentMoreInfoDataProvider(modelToPresenter));
        dataProvider.provideData();
        Mockito.verify(dataProvider).populateWeatherData(currentlyPojo);
    }
}

如果我运行此命令,则在

if(null != apiWeatherData.getCurrently()){

我应该如何向该类中的ProviderData方法提供apiWeatherData


共 (1) 个答案

  1. # 1 楼答案

    如果对生产代码应用简单的重构,我认为您不需要使用PowerMockito:

    public class CurrentMoreInfoDataProvider{
    
    @Override
    public void provideData() {
        WeatherApiResponsePojo apiWeatherData = getApiWeatherData();
        if(null != apiWeatherData.getCurrently()){
            CurrentlyPojo currently = apiWeatherData.getCurrently();
            if(null != currently){
                populateWeatherData(currently);
            }
        }
    }
    
    WeatherApiResponsePojo getApiWeatherData(){
       return WeatherDataSingleton.getInstance().getApiWeatherData();
    }
    

    然后在测试中,期望新方法返回特定对象:

    @RunWith(MockitoJUnitRunner.class)
    public class TestCurrentMoreInfoDataProvider {
    
    
        private CurrentMoreInfoDataProvider dataProvider;
        @Mock
        CurrentMoreInfoInterface.modelToPresenter modelToPresenter;
        @Mock
        WeatherApiResponsePojo apiWeatherDataMock;
    
        private CurrentlyPojo currentlyPojo = new CurrentlyPojo();
        @Test
        public void testPopulateWeatherData(){
    
            dataProvider = PowerMockito.spy(new CurrentMoreInfoDataProvider(modelToPresenter));
    
            doReturn(apiWeatherDataMock).when(dataProvider).getApiWeatherData();
    
            dataProvider.provideData();
            Mockito.verify(dataProvider).populateWeatherData(currentlyPojo);
        }
    }