gpt4 book ai didi

java - 在java中自动化单元测试用例

转载 作者:行者123 更新时间:2023-11-30 06:36:12 25 4
gpt4 key购买 nike

引用this先提问。但似乎我的背景不同。

我会尽量简短。 (只是我发布的代码相当大;)

我有大约 50 多个服务类。并且需要为所有这些编写单元测试用例。在所有这些测试类中,一些测试是常见的。 (删除、查找等)只是对象类型会因服务类而异。

以下示例将清除图片。


考虑以下具有 CRUD 操作的服务类。

public class ObjService {

public Obj addObj(ParamType param, String var) { ... }

public void deleteObj(ParamType param, String var) { ... }

public List<Obj> findAllObj(ParamType param, String var) { ... }

public Obj findById(ParamType param, String var, String objIdToFind) { .. }

public List<Obj> getAllObjs(ParamType param, String var, ObjQuery objQuery) throws Exception { ... }

public Obj updateObj(ParamType param,
String var, Obj objToUpdate) throws Exception { }
}

现在我正在为 ObjService 类编写一个测试用例。 (测试框架 - testNG)

public class ObjServiceTest {

//These methods which will differ across all service classes

@Test
public void testAddObj() throws Exception {
addObj();
}

@Test
public void testUpdateObj() throws Exception {
Obj objToUpdate = addObj();
Obj updatedObj = updateObj(objToUpdate);
}

public Obj addObj() throws Exception {
//add obj test data and return the obj object
}

public Obj updateObj(Obj objToUpdate) throws Exception {
//update obj test data and return the updated obj object
}

//Following methods will be common to all classes. Except the name 'obj'
//e.g. For obj2 it would change to testDeleteObj2() { Obj2 obj2Todelete.... etc}

@Test
public void testDeleteObj() throws Exception {
Obj objToDelete = addObj();
deleteObj(objToDelete);
}

public void deleteObj(Obj objToDelete) throws Exception {
//delete the obj object
}

@Test
public void testFindById() throws Exception {
ObjService client = new ObjService();
List<Obj> objs = dsClient.findAllObj(...);
}

@Test
public void testFindAllObjs() throws Exception {}

@Test
public void testGetObjs() throws Exception {}
}

现在。手动为所有类编写公共(public)方法肯定是一项耗时的工作。那么可以通过做一些自动化来减少吗?

(尽我所能以最不令人费解的方式提出问题)

Edit: 1) The test classes already inherit a BaseTestClass which contains the initial setup needed. So that is a problem.

2) Please don't forget the part, where refactoring is needed across the methods which differ.

最佳答案

听起来您的服务应该实现一些通用接口(interface)。这样您就可以编写一个也是通用的抽象基础测试用例,然后让每个“真正的”服务测试都从它继承,包括继承该抽象类中的测试。

子类的构造函数将为服务、示例查询等传递适当的值。

编辑:对于基类,只需将抽象基测试类子类化为您的现有基类。

为了特化,要么在需要做完全不同的事情时覆盖测试方法本身,要么使测试方法依赖于抽象类中的抽象方法,以便每个具体的子类都可以填充适当的行为。

关于java - 在java中自动化单元测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5119971/

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