简体   繁体   中英

Testing a python class with nosetests

Despite spending hours trawling through the documentation and various blog posts online, I still haven't figured out how to do this.

I have a class:

class ExampleClass(object):
    def __init__(self,x,y):
        self.x = x
        self.y = y

    def add(self):
        return self.x+self.y

    def multiply(self):
        return self.x*self.y

Now let's say I want to write some tests that check whether the methods add and multiply do what I want them to do.

In my tests file I have:

class TestExampleClass(object):
    def setup(self):
        class_object = ExampleClass(1,1)

    def test_add(self):
        assert class_object.add() == 2

    def test_multiply(self):
        assert class_object.multiply() == 1

However, I get a NameError: global name "class_object" is not defined.

I'm really not sure how I'm supposed to achieve what I want, which is to instantiate a class object with some data that I understand and know, and test that the methods on those data are returning what I know they should.

The error you're describing is because your TestExampleClass doesn't have an

def __init__(self):

in it. So it never gets around to actually creating the class_object.

Judging by the way the code is written, I think you want setup(self) to actually be __init__(self)

edit You also need self.x etc everywhere (as noted in a separate answer). This isn't the cause of the error you're reporting, but it will be the cause of the errors you'll see once you put in the __init__ .

So borrowing heavily from the other answer, but adding the __init__ :

class ExampleClass(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def add(self):
        return self.x + self.y

    def multiply(self):
        return self.x * self.y

class TestExampleClass(object):
    def __init__(self):
        self.class_object = ExampleClass(1, 1)

    def test_add(self):
        assert self.class_object.add() == 2

    def test_multiply(self):
        assert self.class_object.multiply() == 1

To make / access the instance variable, you need to qualify the variable with self :

class ExampleClass(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def add(self):
        return self.x + self.y

    def multiply(self):
        return self.x * self.y

class TestExampleClass(object):
    def setup(self):
        self.class_object = ExampleClass(1, 1)

    def test_add(self):
        assert self.class_object.add() == 2

    def test_multiply(self):
        assert self.class_object.multiply() == 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM