Reputation: 9785
Here is the scenario: I generate Random Data in one class and use it as an argument in a method in the same class. How can i use the exact same value in another class ?
Here is a simplified version of my classes:
public class A {
@Test
public void aMethod() {
RandomStringUUID ruuid = new RandomStringUUID();
}
}
Then:
public class B {
@Test
public void bMethod() {
// Want to use ruuid , without instantiating RandomStringUUID
// as i dont want new values, i want the one from class A
}
}
Upvotes: 2
Views: 11121
Reputation: 114757
We sometimes test use helper classes. That could be a solution for your (test) case. So A
wouldn't provide the value to B
but both would obtain the same object from a third class:
public class TestHelper {
private final static RandomStringUUID UUID = new RandomStringUUID();
public static RandomStringUUID getDummyRandomStringUUID() {
return UUID;
}
}
public class A {
@Test
public void aMethod() {
RandomStringUUID ruuid = TestHelper.getDummyRandomStringUUID();
}
}
(and the same with B
)
It's still questionable for testing, because each test run uses a different UUID value, so the tests are not reproduceable. It would be better to define a static UUID that is used for every test run.
Upvotes: 0
Reputation: 9331
Make your variable a public static variable in class A
public static RandomStringUUID RUUID = new RandomStringUUID();
After the beatdown I'm getting in the voting count
private RandomStringUUID uuid;
private createUuid() {
uuid = new RandomStringUUID(); //Or any other way you create it
}
public static RandomStringUUID getRuuidForOtherClassesToCheck() {
return ruuid;
}
Not enough info on the OP's part to infer it's design rules or just a simple JAVA question on how to get a Variable from Class to Class. :D
Upvotes: 2
Reputation: 9008
Either have A give the value to B
public class B {
@Test
public void bMethod(RandomStringUUID ruuid) {
// Want to use ruuid , without instantiating RandomStringUUID
// as i dont want new values, i want the one from class A
}
}
Or have A make it available to be accessed by B, as @sics said
Upvotes: 0
Reputation: 1318
use a static approach:
public class A {
private final static RandomStringUUID ruuid = new RandomStringUUID();
public final static RandomStringUUID getRuuid() {
return ruuid;
}
@Test
public void aMethod() {
RandomStringUUID ruuid = getRuuid();
}
}
and
public class B {
@Test
public void bMethod() {
RandomStringUUID ruuid = A.getRuuid();
}
}
Upvotes: 4