在androidTest案例中如何使用“应用程序对象”? -安卓

时间:2019-05-13 21:06:28

标签: android mockito android-testing

我正在 androidTest 中编写测试用例,并且我的代码具有 public string GetProvinceHtml() { var provinces = GetProvinces(); bool french = Sitecore.Context.Language == Language.DefaultLanguage; var html = "<ul>"; foreach (var prov in provinces) { var url = ""; if (string.IsNullOrEmpty(HttpContext.Current.Request.Url.Query)) { url = string.Format("{1}?province={0}&lang={2}", prov.Code.ToLower(), HttpContext.Current.Request.Url, french ? "fr-CA" : "en-CA"); } else { var nameValues = HttpUtility.ParseQueryString(HttpContext.Current.Request.QueryString.ToString()); if (nameValues["province"] != null) { nameValues.Set("province", prov.Code.ToLower()); } else { nameValues.Add("province", prov.Code.ToLower()); } if (nameValues["lang"] == null) { nameValues.Add("lang", french ? "fr-CA" : "en-CA"); } url = HttpContext.Current.Request.Url.AbsolutePath; url = url + "?" + nameValues; } html += String.Format("<li><a href='{0}'>{1}</a></li>", url, !french ? prov.Name : prov.FrenchName); } html += "</ul>"; return html; } ,因为在单元测试用例中,我无法访问Android框架类,而且我也没有使用 Roboelectric 用于单元测试。

我正在为应用程序对象获取Pattern.EMAIL_ADDRESS,就像在我的NullPointerException中一样,我正在使用此ResetPasswordViewModel对象来获取字符串值形式application。 甚至我都嘲笑了string.xml,但仍然返回null。我尝试使用@Mock Application application,但仍然无济于事。

我想念什么吗?可能是什么问题?

androidTest 情况下如何使用InstrumentationRegistry.getTargetContext()对象? 请参考以下代码:

application

NulllPointerError

成绩

@RunWith(AndroidJUnit4.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ResetPasswordUnitTestsInt {

ResetPasswordViewModel resetPasswordViewModel;
@Rule
public InstantTaskExecutorRule instantTaskExecutorRule = new InstantTaskExecutorRule();
@Mock
Application application;
@Mock
Patterns patterns;

@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    resetPasswordViewModel = new ResetPasswordViewModel(application);
}

@Test
public void a_testEmailIdFieldNegativeCase() {
    resetPasswordViewModel.userName.setValue("");
    resetPasswordViewModel.setErrorVisibilityIfBlankField();
    Assert.assertEquals(true, resetPasswordViewModel.userNameErrorVisibility.getValue());
}
}

1 个答案:

答案 0 :(得分:1)

似乎您错过了androidTest配置中的某些内容(可能在gradle中的某处)。您尝试使用单元测试实践而不是自动化测试。无论如何,以下是基于您的错误的模拟配置示例:

namespace Test
{
    public interface IArbitraryQualifier
    {
        int Qualification { get; }
    }

    public class ArbitraryQualifier : IArbitraryQualifier
    {
        public const int MIN_QUALITY = 1;

        public int Qualification { get; }
    }

    public class Person
    {
        public IArbitraryQualifier ArbitraryQualifier { get; }
        public bool AmIARealBoy => 
            ArbitraryQualifier.Qualification >= Test.ArbitraryQualifier.MIN_QUALITY;
    }
}

当然,将来您还会遇到另一个错误。只需手动配置任何模拟,这对于真正的JEDI来说是很难的方法

相关问题