user1629109 user1629109 - 2 months ago 11
Java Question

How do I prevent a method from being called more than once

Let's say I have these methods

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
}
}


Then I have my
TestNg
test class as below

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();
}
}


Now if I run
T1
and
T2
as part of test suite it will run the
obtainAuth()
method twice (Once in
T1
and Once in
T2
). Since I'm running both tests as part of the same suite it should only run the
obtainAuth()
method and store the returned value which is
AWSCredentials
in a
static
way.

I tried instantiating
obtainAuth()
in a
static
way by declaring a static class level field in
Uploader
class. But it didn't work.

Answer

Basically you add an abstraction. What prevents you from putting a check into your AuthProvider that checks if it already did do its job?

In other words: rework your method to allow for multiple calls; but only the first does something; the other are no-ops: or even simpler:

public class AuthProvider {
  private static final AWSCredentials credentials = new BasicAWSCredentials("key1", "");

  protected AWSCredentials obtainAuth() {
    return credentials;
  }

But well, what would hinder then from making the whole thing static ...