我正在为一个以各种方式创建和作用于实体的服务编写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 **/
}
Run Code Online (Sandbox Code Playgroud)
但是,我的理解是我不能指望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 **/
}
Run Code Online (Sandbox Code Playgroud)
......如果你跟着我
所以我的问题是,编写这些测试的"正确"方法是什么,所以代码干净而优雅?
谢谢,罗布
您可以使用带@Before注释的方法初始化要在测试中使用的实体.然后,使用带@After注释的方法清除/释放测试使用的任何资源.
你可以有:
private Entity entity;
@Before
public void init() {
entity = ...
}
@Test
public void test1() {
// do things to entity
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
261 次 |
| 最近记录: |