mercredi 28 septembre 2016

static variable changes through different tests

Why does a private variable changes though different tests?

For my tests I'm using Groovy and JUnit4.

For my example we are assuming that the tests run in the order that I wrote them. Here is an example with output values:

class Email {
    def get() {
        def timestamp = (System.currentTimeMillis() / 10L).toString().replaceAll("\\.", "");
        return "mail." + timestamp + "@test.com"
    }
}

@RunWith(JUnit4)
class TestA {
    private static def email = new Email().get() // e.g. mail.123@test.com
    static def form = [
        email: email,
        password: 12356
    ]

    @Test
    void "firstTest"() {
        println email // prints mail.123@test.com
        println form.email // prints mail.123@test.com
    }
}

@RunWith(JUnit4)
class TestB {
    private static def email = new Email().get() // e.g. mail.456@test.com
    static def form = [
        login: email,
        password: 12356
    ]

    @Test
    void "secondTest"() {
        println email // prints mail.456@test.com
        println form.login // prints mail.123@test.com
    }
}

Why is it like it is and how do I prevent it?

Aucun commentaire:

Enregistrer un commentaire