gpt4 book ai didi

android - 使用反射为私有(private)方法编写测试

转载 作者:行者123 更新时间:2023-11-28 21:03:29 24 4
gpt4 key购买 nike

我有一个类是 NetworkManager。我有很多 private 方法,我确实需要为它们编写测试。

起初我没有找到任何解决方案来为我的私有(private)方法编写测试。不管怎样,我找到了一种方法来访问我的私有(private)方法并为它们编写一些测试。

我使用反射来访问我的函数并为它们编写测试。有一个简单的私有(private)方法的例子:

 private String myFun (String input){
return input+"hello";
}

有一个测试类,我在里面用到了反射:

@RunWith(AndroidJUnit4.class)
public class NetworkManagerTest {

private static NetworkManager networkManager;
private Context appContext = InstrumentationRegistry.getTargetContext();

private @ADType
int adType = ADType.TYPE_BANNER;


@BeforeClass
public static void setup() {

getInstrumentation().runOnMainSync(new Runnable() {
@Override
public void run() {

networkManager = NetworkManager.getInstance();
networkManager.addNetworkCall(TestUtil.getSampleSystemRequest());

}
});
}

@Test
public void sample() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {

Method method = NetworkManager.class.getDeclaredMethod("myFun", String.class);
method.setAccessible(true);
String output = (String) method.invoke(networkManager, "Ehsan");

Assert.assertEquals("Ehsanhello", output);
}

}

这很好用。但问题是,这种使用反射为私有(private)方法编写测试的方式有多大?

有没有更好的方法来实现这个目标?

最佳答案

But the question is how much is this way okay to write test for private methods with using of reflection?

Is there a better way to achieve this goal?

最常见的方法是放弃该目标。

从历史上看,TDD 的重点一直是验证行为,而不是实现细节。部分原因在于,测试让我们可以自由地更改代码的内部设计,而且充满信心,因为测试会提醒我们注意任何意外的行为更改。

因此,如果我们需要测试以确保某些私有(private)方法中的逻辑是正确的,我们会为依赖于该逻辑的公共(public) API 找到一个用例,并编写测试来衡量公共(public) API 的行为。

我们可以通过向私有(private)方法中注入(inject)一个临时错误来校准测试,并验证测试是否检测到错误。

完成后,我们可以选择通过内联私有(private)方法来重构代码;在这种情况下,所有测试仍应通过,因为我们没有改变测试对象的行为——我们只是移动了细节。

如果您打算积极改进应用程序的内部设计,那么您需要与该内部设计分离的测试。

关于android - 使用反射为私有(private)方法编写测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56846280/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com