I would like to be able to test my application and from what I have read this is best done by creating a class to test the application with. I would hope the testing class should be something I can run using BlueJ without any errors.
I have three classes (not including the testing class)...
1. MyMainMethod (where the program will be run)
public class myMainMethod{
public static void main (String[] args){
TestMyClass1.testCreateMyClass1ArrayList();
}
}
2. MyClass1 (to contain an arraylist of objects type "MyClass2")
import java.util.ArrayList;
class MyClass1 {
private ArrayList<MyClass2> arrayListMyClass1;
MyClass1()
{
arrayListMyClass1 = new ArrayList<>();
}
}
3. MyClass2 (objects to be populated into the array defined by MyClass1)
import java.util.ArrayList;
class MyClass2 {
private String myInformation;
MyClass2()
{
String myInformation = "Information held within the object";
}
}
I would like to test creating an instance of the class MyClass1, so I have created the class...
4. TestMyClass1
class TestMyClass1 {
private MyClass1 myClass1;
public void testCreateMyClass1ArrayList(){
myClass1 = new MyClass1();
}
}
However the test to create an instance of the class "MyClass1" produces the compiler error "Non-static method cannot be referenced from a static context". But imagining my unit test "TestMyClass1" is my main method, I then have no problems instantiating the class "MyClass1" (so the program seems to run as expected).
Can anybody kindly explain why what seems to be a method call from the main method to a class "TestMyClass1" to invoke instances of another class "MyClass1" return this error and propose a solution?
UPDATE: After reading Non static method cannot be referenced from a static context error, can someone kindly confirm if the following is a good or correct implementation for what I'm trying to do?
The updated code is as follows...
1. My Main Method (we create an instance of the class TestMyClass1, where MyClass1 is the class we would like to create an object of to test)
public class myMainMethod{
public static void main (String[] args){
TestMyClass1 testMyClass1 = new TestMyClass1();
}
}
4. TestMyClass1 (we create a class such that we reference an instance of the class MyClass1 when creating an instance of the class TestMyClass1)
class TestMyClass1 {
private MyClass1 myClass1;
TestMyClass1(){
myClass1 = new MyClass1();
}
}