z建成
2020-06-17 11:44
采纳率: 75%
浏览 335

Android 单元测试内部类mock

报错:

java.lang.IncompatibleClassChangeError: android.media.SoundPool and android.media.SoundPool$Builder disagree on InnerClasses attribute

错误定在这一行

mSoundPoolBuilder = PowerMockito.mock(SoundPool.Builder.class);

被测目标代码

public static void playAlarmSound(Context context, int event, int loop) {
    if (abs == null) {
        abs = new AudioAttributes.Builder()
            .setUsage(AudioAttributes.USAGE_MEDIA)
            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
            .build();
    }
    if (mSoundPool == null) {
        mSoundPool = new SoundPool.Builder()
                    .setMaxStreams(1)
                    .setAudioAttributes(abs)
                    .build();
    }

    ........
}

单元测试代码:

@RunWith(RobolectricTestRunner.class)
@Config(manifest=“../../app/src/main/AndroidManifest.xml”)
public class WarningManagerTest {
    private AudioAttributes.Builder absBuilder;
    private AudioAttributes abs;
    private SoundPool.Builder mSoundPoolBuilder;
    private SoundPool mSoundPool;

    @Test
    public void testPlayAlarmSound(){
        absBuilder = PowerMockito.mock(AudioAttributes.Builder.class);
        abs = PowerMockito.mock(AudioAttributes.class);

        mSoundPoolBuilder = PowerMockito.mock(SoundPool.Builder.class);
        mSoundPool = PowerMockito.mock(SoundPool.class);

        //AudioAttributes
        PowerMockito.whenNew(AudioAttributes.Builder.class).withAnyArguments().thenReturn(absBuilder);
        PowerMockito.when(absBuilder.setUsage(anyInt())).thenCallRealMethod();
        PowerMockito.when(absBuilder.setContentType(anyInt())).thenCallRealMethod();
        PowerMockito.when(absBuilder.setUsage(anyInt())).thenReturn(absBuilder);
        PowerMockito.when(absBuilder.setContentType(anyInt())).thenReturn(absBuilder);
        PowerMockito.when(absBuilder.build()).thenReturn(abs);

        //SoundPool
        PowerMockito.whenNew(SoundPool.Builder.class).withAnyArguments().thenReturn(mSoundPoolBuilder);
        PowerMockito.when(mSoundPoolBuilder.setMaxStreams(anyInt())).thenCallRealMethod();
        PowerMockito.when(mSoundPoolBuilder.setAudioAttributes(any(AudioAttributes.class))).thenCallRealMethod();
        PowerMockito.when(mSoundPoolBuilder.setMaxStreams(anyInt())).thenReturn(mSoundPoolBuilder);
        PowerMockito.when(mSoundPoolBuilder.setAudioAttributes(abs)).thenReturn(mSoundPoolBuilder);
        PowerMockito.when(mSoundPoolBuilder.build()).thenReturn(mSoundPool);

        WarningManager.playAlarmSound(context, 0, 0);

    }
}

请帮忙看看什么原因。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题