Android中Mimetype的单元测试用例

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

我正在用Android新编写测试用例,我想在从URL获取Mimetype上编写测试用例。在应用程序模式下可以正常工作,但不能在测试用例中工作,我尝试了不同的方式,但是我没有通过测试用例,请告诉我在哪里出错。任何人都可以提前帮助我。

这是我的代码:MainActivity.java

    public class MainActivity extends AppCompatActivity {
        private static final String TAG = "MainActivity";
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        String url = "www.toyota.com/content/ebrochure/2018/avalon_ebrochure.pdf";
        getContentType(pdf);
        }

        // get mimetype from the url
        public String getContentType(String url) {
            String type = "";
            String extension = MimeTypeMap.getFileExtensionFromUrl(url);
            if (extension != null) {
                type =MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase());
            }
            return type;
        }
}

MainActivityTest.java

import org.junit.Test;
import static junit.framework.Assert.assertEquals;
public class MainActivityTest {
    String url = "www.toyota.com/content/ebrochure/2018/avalon_ebrochure.pdf";
    @Test
    public void getContentType(){
        String result = (new MainActivity()).getContentType(url);
        assertEquals("application/pdf", result);
    }
}

输出:

junit.framework.ComparisonFailure: 
Expected :application/pdf
Actual   :
java android unit-testing
1个回答
0
投票

如果您在运行测试时使用Robolectric模拟Android环境,则需要自己注册媒体类型。默认情况下,模拟的MimeTypeMap为空。

shadowOf(MimeTypeMap.getSingleton()).addExtensionMimeTypMapping("pdf", "application/pdf");
© www.soinside.com 2019 - 2024. All rights reserved.