简体   繁体   English

从 java 中的其他方法调用对象

[英]calling objects from other methods in java

I am a novice programmer and was wondering how I can create a test method that calls the object from the setUp() method above.我是一名新手程序员,想知道如何创建一个从上面的 setUp() 方法调用 object 的测试方法。 Is there a better way to do this where a method is used to initialize the objects and the test method does the testing??是否有更好的方法来执行此操作,其中使用方法初始化对象并且测试方法进行测试?

Any tips are appreciated..任何提示表示赞赏..

public class ProjectTeamRemoveMemberTest {
    
    //Initialize test object
    public static void setUp() {
        Date date = new Date();
        Employee e = new Employee("Alice", date);
        Project p = new Project();
    }

    @Test
    public void removeTeamMember_True_ifMemberIsSelected() {
        setUp();
        assertEquals(true, p.removeTeamMember(e));
    }
}

You can create those variables on class level, assign values in setup and refere to them in a test.您可以在 class 级别上创建这些变量,在设置中分配值并在测试中引用它们。

public class ProjectTeamRemoveMemberTest {
    
    static Date date;
    static Employee e;
    static Project p;

    //Initialize test object
    public static void setUp() {
        date = new Date();
        e = new Employee("Alice", date);
        p = new Project();
    }

    @Test
    public void removeTeamMember_True_ifMemberIsSelected() {
        assertEquals(true, p.removeTeamMember(e));
    }
}

You can use @Before annotation or @BeforeEach (if you use JUnit5)您可以使用@Before注释或@BeforeEach (如果您使用JUnit5)

public class ProjectTeamRemoveMemberTest {公共 class ProjectTeamRemoveMemberTest {

private Employee e;
private Project p;

@Before // will be called before each test mehod
public void createEmployee() {
   e = new Employee("Alice", new Date());
}
@Before 
public void createProject() {
   p = new Project();
}

@Test
public void removeTeamMember_True_ifMemberIsSelected() {
    assertEquals(true, p.removeTeamMember(e));
}

} }

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

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