Saffik
Saffik

Reputation: 1003

JUnit Call a test method in one class from another class

Had a quick look at past questions, couldn't see something similar so here goes:

I also made a mistake in choosing dummy names for this example to illustrate my point, I'll rename them.

I have a class which has a JUnit test:

public class CheckFilter {
    @Test
    public void Run_filter_test() {
        //some code
    } 
}

And then another class:

public class CheckVideoPlays {
    @Test
    public void Play_video_in_full() {
        //some more code here etc
    } 
}

Finally, how do I call these two tests from another class, obviously you can't extend multiple classes.

public class RunAllTests { 
    //How do i call both
    //eg
    //
    //Run_filter_test();
    //Play_video_in_full();
}

Note: I don't want to call the class. Don't want to run as:

@RunWith(Suite.class)

@Suite.SuiteClasses({

CheckFilter.class,

CheckVideoPlays.class

})

Upvotes: 6

Views: 11299

Answers (2)

DwB
DwB

Reputation: 38290

A few things.

  1. Change the name of Sanatize_all_inputs to the (java standard form) camel case, perhaps sanitizeAllImports. When using Java, obey Java.
  2. It seems likely that you will sanitize inputs once per test, which, to me, indicates that you want a class level variable of type ConvertAll in your jUnit test class.
  3. Either use composition (another class level variable of type BaseTestBlammy) or inheritance (extend class BaseTestBlammy) to acquire access to the BaseTestBlammy methods.

Here is an example:

public MyJunitTestKapow
extends BaseTestBlammy
{
    private final ConvertAll convertAll;

    public MyJunitTestKapow()
    {
        convertAll = new ConvertAll();
    }

    @Test
    public void someTest()
    {
        convertAll.sanitizeAllInputs(...);

        ... // do the rest of the test here.
    }
}

Upvotes: 1

Bartosz Bilicki
Bartosz Bilicki

Reputation: 13235

You could make static method in ConvertAll.sanitize then call this method in both ConvertAll.Sanitise_all_inputs test and CheckFilter.Run_filter_test

As better (more maintainable and powerful) solution you may create Sanitiser class with sanitise() method (method may be static or not). Then each class that requires sanitise functionality will call Sanitiser.sanitise. This soltion may be better in long run- you may pass paramethers to sanitise method (or to Sanitiser constructor), Sanitiser may have some internal state, etc

Side note: you may consider migrating to Junit5 (basically it is just change of imported packages). Junit5 has @DisplayName annotation that declares nice test method names (with spaces). So your test methods will respect Java naming convention.

@Test
@DiplayName("Sanitize all inputs")
public void sanitiseAllInputs() {
    //some more code here etc
} 

Upvotes: 0

Related Questions