当java对象从父类调用时,有没有一种方法可以使它在子类的所有方法中都可见?

yws3nbqq  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(166)

在一个测试类中,我使用了一个内置的appiumdriverlocalservice类,它跨三个方法使用,测试运行成功。

public class AppiumServer {
 AppiumDriverLocalService service;

 static String appiumMainJSPath = "/Applications/Appium.app/Contents/Resources/app/node_modules/appium/build/lib/main.js";

 public void startServer() {
 service = AppiumDriverLocalService.buildService(new AppiumServiceBuilder()
         .withAppiumJS(new File(appiumMainJSPath)));

 service.start(); //server starts successfully
 }

 public void testServer() throws FileNotFoundException {
 System.err.println(("The Server URL is: " + service.getUrl().toString()));
 System.err.println(("Is Server Running? : " + service.isRunning())) //Server is running  
}  

  public void stopServer() {
  if (service.isRunning()) {
  service.stop(); //server successfully stopped
    }
  }

现在,在一个子类中,我创建了父类的对象,并从父类调用了方法。如果我在一个方法中调用所有三个方法,那么对象是可见的。

public class LoginTest {

AppiumServer appiumServer = new AppiumServer();

public void startApp() throws MalformedURLException, InterruptedException, FileNotFoundException {
appiumServer.startServer(); //server starts successfully
appiumServer.testServer(); //server is running
Thread.sleep(2000)
appiumServer.stopServer(); //server stops
}

所以,这就是问题所在。如果在多个方法中使用该对象,则它仅在第一个方法中可见,在随后的方法中突然变为null,从而失去可见性。可能有什么问题?

public void startApp() throws MalformedURLException, InterruptedException, FileNotFoundException {
appiumServer.startServer(); //server starts successfully
appiumServer.testServer(); //server is running
}

 public void quitApp() {
 appiumServer.stopServer(); //Throws a NullPointerException. Object visibility is lost
  }
yvgpqqbh

yvgpqqbh1#

现在,在一个子类中,我创建了父类的对象,并从父类调用了方法。如果我在一个方法中调用所有三个方法,那么对象是可见的。
你很困惑,或者至少用错了词。
这是一个子类:

class Dog extends Animal {}

你写的东西没有扩展任何东西-因此 LoginTest 不是的子类 AppiumServer .
我创建了父类的对象,并从父类调用了方法。
所以,那不是你的家长班。如果是这样的话,你就不会想“制造一个物体”——这就是背后的想法 LoginTest extends AppServer logintest已经是appserver了。如果logintest调用 new AppServer() ,您有两个appserver:logintest示例(这是一个appserver-只是一个附加了一些额外行为的示例)和您创建的appserver对象,显然不正确。如果你写信 class LoginTest extends AppiumServer ,您可以自己调用这些方法。毕竟,您是一个appiumserver(打个电话就行了 startServer() ,否 foo. 在它前面)。
鉴于此 LoginTest 很可能不打算成为 AppiumServer ,这里的问题是关于什么是子类/父类的措辞和想法。你有一个名为 LoginTest ,它生成一个appiumserver示例并调用其上的一组方法。这就是全部。在这个故事中没有子类、父类等。

为什么它是空的?

在粘贴的代码中不会这样,但看起来您编写了一些新代码,这些代码并不是针对这个问题运行的。
测试框架通常为每个新测试重新启动,以确保测试的执行顺序不影响测试结果。
这是个好主意,你不应该搞砸。
测试框架具有在一组测试之间共享信息的功能。例如,junit有 @BeforeClass 注解:appiumserver本身的设置和拆卸应该在这里完成,然后每个测试都可以使用 appiumServer 现场。

相关问题