抽象类和抽象单元测试

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

Abstract class and abastract Unitest

问题

以下是您要翻译的内容:

class Vehicule(ABC):
    wheel = None
    roof = None

    def drive():
        use wheel and roof, blabla...

class Car(Vehicule):
    wheel = 4
    roof = True

class Bike(Vehicule):
    wheel = 2
    roof = False
class TestVehicule(ABC, TestCase):
    wheel = None
    roof = None
    factory = None

    def test_how_many_wheel(self):
        self.assertEqual(factory.wheel, self.wheel)

    def test_is_roof(self):
        self.assertEqual(factory.roof, self.roof)

class TestCar(TestVehicule)
    wheel = 4
    roof = True
    factory = CarFactory

class TestBike(TestVehicule)
    wheel = 2
    roof = False
    factory = BikeFactory

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

英文:

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

class Vehicule(ABC):
    wheel = None
    roof = None

    def drive():
        use wheel and roof, blabla...

class Car(Vehicule):
    wheel = 4
    roof = True

class Bike(Vehicule):
    wheel = 2
    roof = False

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

class TestVehicule(ABC, TestCase):
    wheel = None
    roof = None
    factory = None
    
    def test_how_many_wheel(self):
        self.assertEqual(factory.wheel, self.wheel)

    def test_is_roof(self):
        self.assertEqual(factory.roof, self.roof)

class TestCar(TestVehicule)
    wheel = 4
    roof = True
    factory = CarFactory

class TestBike(TestVehicule)
    wheel = 2
    roof = False
    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

class TestVehicle(ABC):
    ...

class TestCar(TestVehicle, unittest.TestCase):
    ...

class TestBike(TestVehicle, unittest.TestCase):
    ...

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

英文:

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

class TestVehicle(ABC):
    ...

class TestCar(TestVehicle, unittest.TestCase):
    ...

class TestBike(TestVehiule, unittest.TestCase):
    ...

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:

确定