简体   繁体   中英

How do you write a unit test for a method that connects to a web service?

I'm using py.test to create unit tests for my application, but I am stuck with a problem.

I create automated web software, so a lot of my methods connect to external servers. I don't want to do this within the test, instead I would rather store the HTML source and test against that.

The question is how do I do this? For example where do I store the test data? Is there anything within py.test that can aid in storing/testing offline data?

The general solution is to use mocking ; replacing the library that calls out to the web service and replacing it with something that acts like that library but returns test versions of normal results.

Use the unittest.mock library to do the mocking; it comes with Python 3.3 and up, or is available as a backport for older Python releases .

Just add a new package to your tests package (where all your unittests are stored) that handles the 'fixtures', the test data to be produced for certain arguments.

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