[英]Unit test private methods in roboletric android
Unit testing private methods may not be good practise but few methods in product has complex login in private methods. 对私有方法进行单元测试可能不是一个好习惯,但是产品中很少有方法在私有方法中具有复杂的登录名。
Can we somehow reflect or call private methods in roboletric in android OR any library similar to roboletric which helps in testing private methods ? 我们能否以某种方式在android的roboletric中反映或调用私有方法,或者可以使用类似于roboletric的任何库来帮助测试私有方法?
Any hints or help would be greatly appreciated 任何提示或帮助将不胜感激
Unit testing private methods may not be good practise, but few methods in product has complex login in private methods.
单元测试私有方法可能不是一个好习惯,但是产品中很少有方法在私有方法中具有复杂的登录名。
The best solution is to extract a class from the complex logic. 最好的解决方案是从复杂逻辑中提取一个类。 Then the class you extract can be tested separately.
然后可以单独测试提取的类。
Can we somehow reflect or call private methods in Roboletric in Android ?
我们可以以某种方式在Android的Roboletric中反映或调用私有方法吗?
If you must use reflection to test your private methods then the procedure in a Robolectric is exactly the same as in a standard JUnit test that uses reflection: 如果必须使用反射来测试私有方法,那么Robolectric中的过程与使用反射的标准JUnit测试中的过程完全相同:
Method method = targetClass.getDeclaredMethod(methodName, argClasses);
method.setAccessible(true);
return method.invoke(targetObject, argObjects);
OR any library similar to Roboletric which helps in testing private methods ?
还是类似于Roboletric的可帮助测试私有方法的库?
Rather than learning a library that helps break good software engineering principles, a better idea may be to learn a dependency injection framework like Dagger 2. Such a DI framework will help you to build smaller classes with strong encapsulation that are more testable. 与其学习有助于打破良好软件工程原理的库,不如学习一个像Dagger 2这样的依赖注入框架,这是一个更好的主意。这样的DI框架将帮助您构建具有更强可封装性的较小类,并具有更强的封装性。 Then you won't have the problem of having private methods to test in the first place.
这样一来,您就不会有使用私有方法进行测试的问题。
There are some links to tools to help test private methods in the answers to this question 在此问题的答案中有一些工具链接可帮助测试私有方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.