PyCharm提示“No tests were found”,单元测试无法被检测问题求助
Hey there, I totally get how frustrating it is to spend hours writing tests only for PyCharm to not detect them. Let’s walk through the most common fixes that usually resolve this headache:
Check naming conventions first
PyCharm relies on standard naming rules to pick up tests by default:- Test files need to start with
test_(e.g.,test_user_service.py) - Test methods/classes must also start with
test_(e.g.,test_create_user()orclass TestUserService:)
If your files/methods don’t follow this pattern, PyCharm will skip over them.
- Test files need to start with
Verify your test framework configuration
- Open PyCharm’s Settings (File > Settings, or press
Ctrl+Alt+Son Windows/Linux,Cmd+,on Mac) - Navigate to Tools > Python Integrated Tools
- Under the Testing section, make sure the default test runner matches the framework you’re using (e.g.,
pytestif you wrote pytest tests,unittestfor standard library tests) - If you’re using pytest, double-check that it’s installed in your project’s virtual environment (
pip install pytest—PyCharm can’t detect the framework if it’s missing)
- Open PyCharm’s Settings (File > Settings, or press
Mark test directories as Test Sources Root
If your tests live in a subdirectory (liketests/), PyCharm might not scan it by default:- Right-click your test directory in the Project pane
- Select Mark Directory as > Test Sources Root
This tells PyCharm to prioritize scanning this folder for test files.
Clear PyCharm’s cache
Cached data can sometimes break test detection. Try this:- Go to File > Invalidate Caches...
- Select Invalidate and Restart
This will wipe PyCharm’s cached data and restart the IDE—this fixes a surprising number of weird detection issues.
Check for syntax errors in your test code
If your test files have syntax mistakes (like incorrect indentation, undefined variables, or missing imports), PyCharm can’t parse them properly, so it won’t detect any tests. Run your tests manually in the terminal first to confirm they’re valid:- For unittest:
python -m unittest path/to/test_file.py - For pytest:
pytest path/to/test_file.py
Fix any errors before trying again in PyCharm.
- For unittest:
Confirm your virtual environment is set up correctly
Make sure PyCharm is using the same virtual environment where you installed your test framework:- Go to Settings > Project: [Your Project Name] > Python Interpreter
- Check that
pytest(if using it) is listed in the installed packages - If you need to switch environments, use the dropdown menu to select the correct one, then restart PyCharm.
内容的提问来源于stack exchange,提问作者Jakub Gawel

