Robolectric,android api似乎没有被调用

问题描述 投票:0回答:1

带空字符串的MediaMetadataRetriever:setDataSource(string)必须抛出IllegalArgumentException()。但是,如果从我的robolectric测试开始,它不会抛出任何异常。

测试类:

@RunWith(RobolectricTestRunner::class)
class MyActivityTest {

    private val context: Context = ApplicationProvider.getApplicationContext()

    @get:Rule
    val exception = ExpectedException.none()

    @Test
    fun test_GivenFilePathEmpty_ButNoException() {
        // no exception is expected

        // Given
        val filePath = ""
        // val filePath = null // This should also throw Exception

        // When
        val controller = Robolectric.buildActivity(
                MyActivity::class.java
        ).setup()

        // Then
        assertNotNull(controller.visible())
    }

my activity.Java

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        mediaMetadataRetriever = new MediaMetadataRetriever();
        filePath = ""
        mediaMetadataRetriever.setDataSource(filePath);

    }

AOSP的MediaMetadataRetriever.java:

public void setDataSource(String path) throws IllegalArgumentException {
    if (path == null) {
        throw new IllegalArgumentException();
    }

    try (FileInputStream is = new FileInputStream(path)) {
        FileDescriptor fd = is.getFD();
        setDataSource(fd, 0, 0x7ffffffffffffffL);
    } catch (FileNotFoundException fileEx) {
        throw new IllegalArgumentException();
    } catch (IOException ioEx) {
        throw new IllegalArgumentException();
    }
}

是因为robolectric无法弄清楚文件系统吗?或者是因为AOSP API并没有真正从RobolectricTestRunner调用?

android unit-testing robolectric junit5
1个回答
0
投票

事实证明,Android API实际上并没有通过Robolectric调用。所以我制作了自定义阴影来模拟API。

@Implements(MediaMetadataRetriever::class)
class ShadowMediaMetaDataRetriever {

    companion object {
        const val INVALID_FILE_PATH = "invalid_file_path"
    }

    @Implementation
    fun setDataSource(path: String?) {
        if (path == null) {
            throw IllegalArgumentException()
        }
        if (path == INVALID_FILE_PATH) {
            throw IllegalArgumentException()
        }
        if (path == "") {
            throw IllegalArgumentException()
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.