gpt4 book ai didi

junit - "correct"这组JUnit测试的写法是什么?

转载 作者:行者123 更新时间:2023-12-04 08:15:08 27 4
gpt4 key购买 nike

我正在为以多种方式创建和作用于实体的服务编写 JUnit 测试。我希望我的测试能够尝试多种不同的事件组合。我有这样的东西:

test1() {
/** create entity **/
/** assert **/
}

test2() {
/** do X to entity **/
/** assert **/
}

test3() {
/** do X again to entity, expect failure **/
/** assert **/
}

test4() {
/** do Y to entity, expect success **/
/** assert **/
}

但是,我的理解是我不能期望 JUnit 以正确的顺序运行测试,并且每个测试都应该完全独立。

但是如果我让每个测试都自包含,那么就会有很多重复代码,运行时间会很长,而且维护起来会更困难……例如:

test1() {
/** create entity **/
/** assert **/
}

test2() {
/** create entity **/
/** do X to entity **/
/** assert **/
}

test3() {
/** create entity **/
/** do X to entity **/
/** do X again to entity, expect failure **/
/** assert **/
}

test4() {
/** create entity **/
/** do X to entity **/
/** do X again to entity, expect failure **/
/** do Y to entity, expect success **/
/** assert **/
}

...如果你关注我。

所以我的问题是,编写这些测试以使代码干净优雅的“正确”方法是什么?

谢谢罗布

最佳答案

您可以使用 @Before 注释方法来初始化要在测试中使用的实体。然后,使用 @After 注释方法清除/释放测试使用的任何资源。

你可以:

private Entity entity;

@Before
public void init() {
entity = ...
}

@Test
public void test1() {
// do things to entity
...
}

关于junit - "correct"这组JUnit测试的写法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11194941/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com