I want to know how I should declare Objects as a field when I want to use them in different test cases.
- standard declaration with 'private'
- final / not final
- static / non static
And if there is a choice how I really should do that, please explain?
CodePudding user response:
lets say i just want to have an simple id as a string which i can use everytime, instead of creating a new String in each test.
Yeah, you can share or create class with fields which have constant values for test cases.
If this variable is used just for some related bunch of tests, then you can create base abstract class and write getter for it. Let me show an example:
public abstract class BaseTest
{
private string _id = "1";
public string GetId()
{
return _id;
}
}
So you will inherit this BaseTest
class in related bunch of tests. This approach uses inheritance.
In addition, you can create a class with constant values:
public class Constant
{
public static final String WELCOME_MESSAGE = "Hello, welcome to the server";
}
And then use this variables in any place you want.
CodePudding user response:
Assuming unit tests, they should be stand-alone, and unordered.
Hence the only fields may be constants, static final String ID_A = "Ahmed";
.
The same for constant objects.
However you can run a setup @BeforeEach
(junit 5) and tear-down @AfterEach
method automatically for every test.
Use that for a database connection and such.
For the rest it often makes sense to have a couple of methods delivering more complex (like hierarchical data). Especially if not every test uses that data, so the object is not suitable a field filled in a setup method.