newToJava
newToJava

Reputation: 173

Moving test data from main to another class in Java

I have created a membership record system in Java and currently populate the hard coded test data within the main but wish to add this test data into a separate class and call that class in. Is it common to have a separate test data class or is this something which is initialised in the main? Any ideas or sources you can point me to?

Current Driver Class:

public static void main(String[] args) {

Member jane = new Member ("jane");
Member alex = new Member ("alex");
Member mike = new Member ("mike");

Set<Member> members = new HashSet<Member >();
members.add(jane);
members.add(alex);
members.add(mike);

What I'd like to have is something like:

public static void main(String[] args) {

TestData tdata1 = new TestData();
tdat1.TestData(); 


Public Class TestData {

Member jane = new Member ("jane");
Member alex = new Member ("alex");
Member mike = new Member ("mike");

Set<Member> members = new HashSet<Member>();
members.add(jane);
members.add(alex);
members.add(mike);

Upvotes: 2

Views: 474

Answers (2)

Tudor
Tudor

Reputation: 62439

I'm not sure I understand what you intend to do but I guess it's something like:

public class Main {
    public static void main(String[] args) {

        TestData tdata1 = new TestData();
        tdat1.test(); 
    }
}

And in TestData.java:

public class TestData {

    public void test() {
        Member jane = new Member ("jane");
        Member alex = new Member ("alex");
        Member mike = new Member ("mike");

        Set<Member> members = new HashSet<Member>();

        members.add(jane);
        members.add(alex);
        members.add(mike);
    }
}

Anyway, you should just do JUnit tests for each operation instead.

Upvotes: 0

Miquel
Miquel

Reputation: 15675

Have you considered unit testing? You could use junit to create a test method that loads in the hardcoded test data and tests it out. This keeps your program free of test code (by cleaning up the main) and gets you going on implementing tests.

Alternatively, how about creating a small class that lets you load a dataset file onto your membership record system? This way, you could load that file (with your hardcoded test values) and you'd still a potentially useful way of initializing records once your software's finished. Please do that only if that feature makes sense!

Upvotes: 2

Related Questions