How to Test Lambda Functions
While, due to their nature, lambda
functions will generally be relatively simple, there may be times when you need to test them. Python lambdas can be tested similarly to regular functions.
It’s possible to use both unittest
and doctest
. The unittest
module handles Python lambda functions similarly to regular functions. In this lesson, you’ll see how to use unittest
to test lambda
functions.
00:01
Testing lambda functions. While due to their nature lambda functions will generally be simple, there may be times when you need to test them. Fortunately, lambda functions can be tested in a similar manner to regular functions, and the unittest
module handles lambda functions in a similar manner to regular functions, which you’re going to see next.
00:27
Now you’re going to see a demonstration of unit testing of a lambda function. The first thing to do will be to import unittest
, and then create the lambda function which we’re going to test.
00:50 Now to create some test cases.
01:09
There’s the first test, just to test that it does square 2
to 4
. Test that squaring 0
gives us 0
. And test that squaring a negative gives us a positive result.
01:46 Finally, running the unit tests.
02:01
And you can see the tests pass satisfactorily. One useful tip you may not know about is by setting the parameter verbosity=2
, you can see which tests are being run, rather than just seeing full stops (.
).
Become a Member to join the conversation.
Sandhya on Jan. 12, 2020
Gr8 One.