如何防止多次调用方法

时间:2016-09-15 18:22:23

标签: java testng

假设我有这些方法

public class AuthProvider {
    protected AWSCredentials obtainAuth() {
        AWSCredentials credentials = new BasicAWSCredentials("key1", "");
        return credentials;
    }
}

public class Uploader extends AuthProvider {
    public void uploadFile() {
        obtainAuth();
        //code to upload file
    }
}

然后我有TestNg测试类,如下所示

public class T1 {
    @Test
    public void runTest1() {
        Uploader uploader = new Uploader();
        uploader.uploadFile();
    }
}

public class T2 {
    @Test
    public void runTest1() {
        Uploader uploader = new Uploader();
        uploader.uploadFile();
    }
}

现在,如果我将T1T2作为测试套件的一部分运行,它将运行obtainAuth()方法两次(一次进入T1一次进入T2 )。由于我将两个测试作为同一套件的一部分运行,因此它应该只运行obtainAuth()方法并以AWSCredentials方式存储返回的static值。

我尝试通过在obtainAuth()类中声明一个静态类级别字段,以static方式实例化Uploader。但它没有用。

2 个答案:

答案 0 :(得分:1)

基本上你添加一个抽象。什么阻止您检查您的AuthProvider,检查它是否已经完成其工作?

换句话说:重写你的方法以允许多次通话;但只有第一个做某事;另一个是无操作:甚至更简单:

// Get a reference to our posts
Firebase ref = new Firebase("https://docs-examples.firebaseio.com/web/saving-data/fireblog/posts");
// Attach an listener to read the data at our posts reference
ref.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {
        System.out.println(snapshot.getValue());
    }
    @Override
    public void onCancelled(FirebaseError firebaseError) {
        System.out.println("The read failed: " + firebaseError.getMessage());
    }
});

但是,那会阻碍整个事情变得静止......

答案 1 :(得分:0)

为什么不这样做

public class AuthProvider {
    private static AWSCredentials credentials = new BasicAWSCredentials("key1", "");
    protected AWSCredentials obtainAuth() {
        return credentials;
    }
}