简体   繁体   English

Java变量未在JUnit测试类中分配

[英]Java variable not assigned in JUnit Test Class

I found something strange in my project. 我在项目中发现了一些奇怪的东西。 I create a test class using JUnit to test my service layer. 我使用JUnit创建一个测试类来测试我的服务层。 The service layer itself is not my question. 服务层本身不是我的问题。 My problem is, I don't know why after I assigned a value to an int variable in my first test method, and then when I try to use that value in the second test method, the variable value is 0 我的问题是,我不知道为什么在第一个测试方法中将一个值分配给int变量后,当我尝试在第二个测试方法中使用该值时,变量值是0

Executed in order because I use @FixMethodOrder(MethodSorters.NAME_ASCENDING) 因为我使用@FixMethodOrder(MethodSorters.NAME_ASCENDING)所以按顺序执行

int id;

@Test
public void firstMethodToTest() {
    id = 10;
    System.out.println(id); // here printed correctly 10
}

@Test
public void secondMethodToTest() {
    System.out.println(id); // here printed 0
}

I also try to change int to Integer but it returns null not 0 anymore. 我也尝试将int更改为Integer但它不再返回null而不是0 I wonder if in JUnit Test class like this, Java variable acts differently. 我想知道在这样的JUnit Test类中,Java变量的行为是否不同。 Thanks. 谢谢。

Thanks to @Ivan for giving me a clue to the answer 感谢@Ivan给我一个答案的线索

For each test method (the method annotated with @Test ), a new instance of YourTestClass will be created. 对于每个测试方法(用@Test注释的方法),将创建YourTestClass的新实例。 This is the behavior of Junit. 这是Junit的行为。

So, the point is if you want to use a class member for all test methods, just declare the variable as static. 因此,重点是,如果要对所有测试方法使用类成员,只需将变量声明为静态。 In my case: static int id; 就我而言: static int id;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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