如何为从基类继承的所有类进行通用单元测试?

时间:2022-09-25 10:24:05

I am creating a base class (or base entity) since all my database tables will have a companyID field.

我正在创建一个基类(或基本实体),因为我的所有数据库表都有一个companyID字段。

In my unit tests, I have to make sure the companyID value is correct.

在我的单元测试中,我必须确保companyID值是正确的。

If I am returning a list of objects, all the companyIDs should be the same.

如果我返回一个对象列表,那么所有的companyID应该是相同的。

Is there a generic way of me writing a test that will loop through all the values, that I could use across all my objects? (they will all inherit from a base class that will have a companyID property).

有没有一种通用的方式来编写一个测试来循环遍历所有值,我可以在所有对象中使用它? (它们都将从具有companyID属性的基类继承)。

2 个解决方案

#1


Yes; write a function that will loop through all the objects in a list, cast the objects to the base class, verify the cast was successful, and test that the CompanyID is valid. You may have to write different unit test classes for each way of retrieving the list of objects, but once the list is received, you can call a common function from each of those tests.

是;编写一个循环遍历列表中所有对象的函数,将对象强制转换为基类,验证转换是否成功,并测试CompanyID是否有效。您可能必须为检索对象列表的每种方法编写不同的单元测试类,但是一旦收到列表,您就可以从每个测试中调用一个公共函数。

#2


one way would be to implement an interface that has the companyId field, then you return a list of that interface, that way you don't have to worry about what the actual type is

一种方法是实现具有companyId字段的接口,然后返回该接口的列表,这样您就不必担心实际类型是什么

#1


Yes; write a function that will loop through all the objects in a list, cast the objects to the base class, verify the cast was successful, and test that the CompanyID is valid. You may have to write different unit test classes for each way of retrieving the list of objects, but once the list is received, you can call a common function from each of those tests.

是;编写一个循环遍历列表中所有对象的函数,将对象强制转换为基类,验证转换是否成功,并测试CompanyID是否有效。您可能必须为检索对象列表的每种方法编写不同的单元测试类,但是一旦收到列表,您就可以从每个测试中调用一个公共函数。

#2


one way would be to implement an interface that has the companyId field, then you return a list of that interface, that way you don't have to worry about what the actual type is

一种方法是实现具有companyId字段的接口,然后返回该接口的列表,这样您就不必担心实际类型是什么