抽象类和抽象单元测试

huangapple go评论95阅读模式
英文:

Abstract class and abastract Unitest

问题

以下是您要翻译的内容:

  1. class Vehicule(ABC):
  2. wheel = None
  3. roof = None
  4. def drive():
  5. use wheel and roof, blabla...
  6. class Car(Vehicule):
  7. wheel = 4
  8. roof = True
  9. class Bike(Vehicule):
  10. wheel = 2
  11. roof = False
  1. class TestVehicule(ABC, TestCase):
  2. wheel = None
  3. roof = None
  4. factory = None
  5. def test_how_many_wheel(self):
  6. self.assertEqual(factory.wheel, self.wheel)
  7. def test_is_roof(self):
  8. self.assertEqual(factory.roof, self.roof)
  9. class TestCar(TestVehicule)
  10. wheel = 4
  11. roof = True
  12. factory = CarFactory
  13. class TestBike(TestVehicule)
  14. wheel = 2
  15. roof = False
  16. factory = BikeFactory

目标是在TestVehicule中编写测试,并在其他类中继承并更改变量,使用子变量执行所有测试。

英文:

I use Django Rest Framework and I wrote something like this:

  1. class Vehicule(ABC):
  2. wheel = None
  3. roof = None
  4. def drive():
  5. use wheel and roof, blabla...
  6. class Car(Vehicule):
  7. wheel = 4
  8. roof = True
  9. class Bike(Vehicule):
  10. wheel = 2
  11. roof = False

It's working good and I want to write unitest with it.I want to write someting similar:

  1. class TestVehicule(ABC, TestCase):
  2. wheel = None
  3. roof = None
  4. factory = None
  5. def test_how_many_wheel(self):
  6. self.assertEqual(factory.wheel, self.wheel)
  7. def test_is_roof(self):
  8. self.assertEqual(factory.roof, self.roof)
  9. class TestCar(TestVehicule)
  10. wheel = 4
  11. roof = True
  12. factory = CarFactory
  13. class TestBike(TestVehicule)
  14. wheel = 2
  15. roof = False
  16. factory = BikeFactory

The goal is to write tests in TestVehicule and inherit in others class change variable and do all the tests with the child variable

答案1

得分: 1

最简单的解决办法是仅为您的非抽象类继承TestCase

  1. class TestVehicle(ABC):
  2. ...
  3. class TestCar(TestVehicle, unittest.TestCase):
  4. ...
  5. class TestBike(TestVehicle, unittest.TestCase):
  6. ...

从技术上讲,如果您只希望unittest忽略它的用例,那么您的TestVehicle甚至不需要是抽象的。

英文:

The easiest way around the problem would be to only inherit TestCase for your non-abstract classes:

  1. class TestVehicle(ABC):
  2. ...
  3. class TestCar(TestVehicle, unittest.TestCase):
  4. ...
  5. class TestBike(TestVehiule, unittest.TestCase):
  6. ...

Technically, your TestVehicle doesn't even need to be abstract at this point, if all you want is for unittest to ignore its cases.

huangapple
  • 本文由 发表于 2023年3月3日 22:43:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75628491.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定