Test development: writing tests for private / protected variables

I am studying TDD and I have a question about private / protected variables. My question is: If the function I want to test works with a private variable, how can I test it?

Here is an example I'm working with:

I have a class called Tablethat contains an instance variable with a name internalRepresentationthat is a 2D array. I want to create a function called multiplyValuesByNthat multiplies all the values ​​in a 2D array by an argument n.

So, I am writing a test for it (in Python):

def test_multiplyValuesByN (self):  
    t = Table(3, 3) # 3x3 table, filled with 0's
    t.set(0, 0, 4) # Set value at position (0,0) to 4
    t.multiplyValuesByN(3)

    assertEqual(t.internalRepresentation, [[12, 0, 0], [0, 0, 0], [0, 0, 0]])

Now, if I make it internalRepresentationprivate or secure, this test will not work. How should I write a test, so it does not depend on internalRepresentation, but still checks that it looks correct after the call multiplyValuesByN?

+3
source share
4 answers

You should not depend on the internal representation of the object. That is why it is marked as private or protected. See what observed changes are made to t when you call t.multiplyValuesByN (3). Then check what you can observe.

def test_multiplyValuesByN (self):  
    t = Table(3, 3) # 3x3 table, filled with 0's
    t.set(0, 0, 4) # Set value at position (0,0) to 4
    t.multiplyValuesByN(3)

    assertEqual(t.get(0,0), 12)
+10
source

If it is internal, then this is nobodys business outside the class and includes tests.

TDD API , .

, , .

: setup - operation - check (- teardown)

.

. , .

+3

, : ( ). .

TDD API, . , , , . , - . , , , API, ( , ).

+3

/. , , . , .

(, ) , , . .

0

Source: https://habr.com/ru/post/1750192/


All Articles