How to create test objects in tests?
I'm creating unittests to a payment process. There is about 20 unit unittests to write -some positives cases and some negatives.
example:
payment_screen=PaymentScreen()
and there I few conceptions.
First - create a Payer object with giving attributes:
payer=Payer(last_name,country_code)
country_code is important, because system doesn't allow to sending items to other countries
Second
payer=Payer.return_correct_payer()
something like:
class Payer:
@staticmethod
开发者_如何学Python def return_correct_payer():
payer=Payer()
payer.country_code='US'
payer.last_name='Smith'
and in both options
payment_screen.fill_payer_data(payer)
And an another conception:
in payment_screen just create two methods:
fill_payer_data_with_correct_data()
and
fill_payer_data_with_uncorrect_data()
Which one is the best? Or maybe you have another idea(I'm sure that you have)
EDIT
Thanks for your replies, but it's not what I need. I just don't want create object Pax in every test case with giving attributes.
I have 20 test cases so now I must write 20 times :
payer=Payer('Smith','US')
I don't want duplicate my code
Maybe what you are looking for is some kind of mocking framework. Then when you test PaymentScreen
, you can mock out Payer
. For more about mocking frameworks for python look here: What is your favorite Python mocking library?.
Hey.
Probably answer with mocks is what you need in the first place, but I want to show how I create objects in my tests.
So if I need a object with given parameters I use BuilderPattern (actually modified BuilderPattern from GOF), which looks like this:
class User {
private string firstName;
private string lastName;
public User(){};
//now the essence
public User withFirstName(strFirstName) {
this.firstName = strFirstName;
return this;
}
public User withLastName(strLastName) {
this.lastName = strLastName;
return this;
}
//some other stuff
}
Then I initiate object with:
User testUser1 = new User()
.withFirstName("John")
.withLastName("Doe");
and then I do with it, what I need.
P.S. Sorry for code not being python syntax... but you should get it
精彩评论