0

I tried to test a file named calc.py using unit testing

import unittest
import calc
class TestCalc(unittest.TestCase):
    
    def test_add(self):
        result = calc.add(10,5)
        self.assertEqual(result,15)

What does self refer to in this code?

  • 5
    Does this answer your question? [What is the purpose of the word 'self'?](https://stackoverflow.com/questions/2709821/what-is-the-purpose-of-the-word-self) – Tirth Patel Jun 26 '20 at 01:29
  • Hm, I forgot I could single-handedly reopen a question. Anyway, I voted to do so because I suspect the question is more along the lines of "Where does the instance of `TestCase` come from?". – chepner Jun 26 '20 at 01:38

1 Answers1

1

It refers to the instance of that invokes the method, in this case an instance of TestCalc. However, you never see the instances specifically, unless you write your own test runner. Otherwise, you typically only interact with the instance (aside from calling the various assert* methods) if you override setUp to configure the fixture.

For example,

class MyTest(unittest.TestCase):
    def setUp(self):
        self.x = SomeClass()

    def test_foo(self):
        self.assertEqual(self.x.foo(), 3)

    def test_bar(self):
        self.assertEqual(self.x.bar(), 6)

x is an instance of a class that you want to use in multiple tests. Rather than call x = SomeClass() in every test method, you call it once in setUp and save the result as an attribute of the test case itself, making it available to each test method.

chepner
  • 497,756
  • 71
  • 530
  • 681