简体   繁体   中英

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

I have a junit test testArchive(). The Junit test tests the archive() method that archives a 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() which emails the URL. But the URL is turning out to be null, though its defined as a class variable

Can you please let me know how I need to correct my Junit test for send email?

Thank you

Keep in mind that:

  • Test cases should not have side effects: the .archive() looks like will produce side effects
  • Test cases should not assume an execution order of other test cases: your testSendEmail seems to assume testArchive is executed first, which is wrong
  • Test cases should not depend on external factors: the getService calls looks like an external (uncontrolled) factor
  • Test cases should be independent and self-contained

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

Short answer:

You should really not do that.

Detailed answer:

Unit tests (and therefore JUnit tests as well) are intended to run separately and independently from each other. Each test should check only one method, regardless of result of another method or another test. So in your case, method testSendEmail() should use some hard coded URL, or better few different URLs.

我删除了第二个JUnit测试并将测试合并为1.存档和电子邮件都将在一次测试中发生。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM