英文:
How can I use the @BeforeEach method for testing in Java?
问题
我正在学习使用JUnit5进行测试驱动开发。在我的阅读材料中写道:“注解添加在方法上以指定其行为。我们经常遇到的一个常见情况是,我们必须为每个测试创建一个新对象。我们可以不在每个测试方法中执行此操作,而是可以创建一个名为setUp()的新方法,然后添加@BeforeEach注解。这将确保在每个测试方法之前执行此方法。”但是我不知道如何在一个方法中使用另一个方法中的对象。请帮忙一下。这是我的代码:
@BeforeEach
public void setUp(){
IntSet set = new IntSet(4);
}
@Test
public void testIntSet(){
assertEquals(set.getCapacity(), 4); //在这里出错:无法解析符号'set'
}
注意:我只翻译了你提供的代码部分,其他内容我没有进行翻译。
英文:
I am learning Test Driven Development with JUnit5. In my reader this is written: " Annotations are added above a method to specify its behavior. A common scenario we find ourselves in is that
we have to create a new object for each test. Instead of doing this in each test method, we can create a new method called setUp() for example, and add the @beforeEach annotation. This will make sure that this method is executed before each test method." But I don't know how can I use an object from a method in another method. Any help, please? This is my code:
@BeforeEach
public void setUp(){
IntSet set = new IntSet(4);
}
@Test
public void testIntSet(){
assertEquals(set.getCapacity(), 4); //error here: Cannot resolve symbol 'set'
}
答案1
得分: 3
你所有的测试都在一个类中,对吗?将其变为一个属性/实例变量:
class SomeTests {
IntSet set;
@BeforeEach
public void setUp() {
set = new IntSet(4);
}
@Test
public void testIntSet() {
assertEquals(set.getCapacity(), 4);
}
}
英文:
You have all your tests in a class, right? Make it a property/instance variable:
class SomeTests {
IntSet set;
@BeforeEach
public void setUp() {
set = new IntSet(4);
}
@Test
public void testIntSet() {
assertEquals(set.getCapacity(), 4);
}
}
</details>
# 答案2
**得分**: 2
你必须在测试类中声明 `IntSet set` 作为一个字段。然后,你可以在 `@BeforeEach` 方法中初始化这个字段。
```java
class MyTest {
private IntSet set;
@BeforeEach
public void setUp() {
set = new IntSet(4);
}
@Test
public void testIntSet() {
assertEquals(set.getCapacity(), 4); // 在这里有错误:无法解析符号 'set'
}
}
英文:
You have to declare IntSet set
as a field in your test class. Then, you can initialize the field in the @BeforeEach method.
class MyTest{
private IntSet set;
@BeforeEach
public void setUp(){
set = new IntSet(4);
}
@Test
public void testIntSet(){
assertEquals(set.getCapacity(), 4); //error here: Cannot resolve symbol 'set'
}
}
答案3
得分: 1
你需要在 setUp()
方法外部声明你的变量。这样它可以在任何方法中访问。
private IntSet set;
@BeforeEach
public void setUp(){
set = new IntSet(4);
}
@Test
public void testIntSet(){
assertEquals(set.getCapacity(), 4); // 这里有错误:无法解析符号 'set'
}
英文:
You need to declare your variable outside of the setUp()
method. This way it is accessible for any method.
private IntSet set;
@BeforeEach
public void setUp(){
set = new IntSet(4);
}
@Test
public void testIntSet(){
assertEquals(set.getCapacity(), 4); //error here: Cannot resolve symbol 'set'
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论