JUnit | How to pass parameters returned from one Junit test to another JUnit test

I have junit test testArchive (). The Junit test examines the archive () method, which archives the file and returns the URL to it as a String. The url is defined as an instance variable inside the Junit test class.

class Prepare {    
    private String url = "";

    @Test
    public void testArchive() {
        String url = getService().archive();
    }

    @Test
    public void testSendEmail() {
        getService().sendEmail(url) // Url is turning out to be null
    }
} // end of class

      

I am writing another Junit test for sendEmail () that sends a url. But the url turns out to be null even though its defined as a class variable

Could you please let me know how I need to fix my Junit test for sending email?

thank

+3


source to share


3 answers


The short answer is:

You really shouldn't be doing this.



Detailed answer:

Unit tests (and thus JUnit tests) are designed to work separately and independently of each other. Each test should only test one method, regardless of the result of another method or another test. So in your case, the method testSendEmail()

should be using some kind of hard url or several different urls.

+2


source


Please be aware that:

  • Test cases shouldn't have side effects: looks like .archive()

    , will create side effects
  • Test cases should not take the order of execution of other test cases: yours testSendEmail

    seems to assume that it testArchive

    is executed first, which is not correct
  • Testing should not depend on external factors: calls getService

    look like an external (uncontrollable) factor
  • Test cases must be independent and self-contained


Instead of one test depending on the result of the other, you can use a private helper method that both test cases can call.

+3


source


I removed the second JUnit test and merged the tests into 1. Both archive and email will pass in the same test.

0


source







All Articles