I have a class like the following:
class A:
def __init__(self, arg1, arg2, arg3):
self.a=arg1
self.b=arg2
self.c=arg3
# ...
self.x=do_something(arg1, arg2, arg3)
self.y=do_something(arg1, arg2, arg3)
self.m = self.func1(self.x)
self.n = self.func2(self.y)
# ...
def func1(self, arg):
# do something here
def func2(self, arg):
# do something here
As you can see, initializing the class needs to feed in arg1, arg2, and arg3. However, testing func1 and func2 does not directly require such inputs, but rather, it's simply an input/output logic.
In my test, I can of course instantiate and initialize a test object in the regular way, and then test func1 and func2 individually. But the initialization requires input of arg1 arg2, arg3, which is really not relevant to test func1 and func2.
Therefore, I want to test func1 and func2 individually, without first calling __init__
. So I have the following 2 questions:
- What's the best way of designing such tests? (perferably, in py.test)
- I want to test func1 and func2 without invoking
__init__
. I read from here thatA.__new__()
can skip invoking__init__
but still having the class instantiated. Is there a better way to achieve what I need without doing this?
NOTE:
There have been 2 questions regarding my ask here:
- Is it necessary to test individual member functions?
- (for testing purpose) Is it necessary to instantiating a class without initializing the object with
__init__
?
For question 1, I did a quick google search and find some relevant study or discussion on this:
- Unit Testing Non Public Member Functions
- (PDF) Incremental Testing of Object-Oriented Class Structures.
We initially test base classes having no parents by designing a test suite that tests each member function individually and also tests the interactions among member functions.
For question 2, I'm not sure. But I think it is necessary, as shown in the sample code, func1 and func2 are called in __init__
. I feel more comfortable testing them on an class A object that hasn't been called with __init__
(and therefore no previous calls to func1 and func2).
Of course, one could just instantiate a class A object with regular means (testobj = A()) and then perform individual test on func1 and func2. But is it good:)? I'm just discussing here as what's the best way to test such scenario, what's the pros and cons.
On the other hand, one might also argue that from design perspective one should NOT put calls to func1 and func2 in __init__
in the first place. Is this a reasonable design option?