如何进行单元测试以及与Django和FastApi等框架中的集成测试有何不同?
假设我有这样的fastapi应用程序(该代码是从文档中获取的):
app = FastAPI()
@app.get("/foo")
async def read_main():
return {"msg": "Hello World"}
我相信有两种测试此观点的方法。第一个是使用客户端对象。例如:
client = TestClient(app)
def test_read_main():
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"msg": "Hello World"}
但是,我认为这不是单位测试。这更像是一项集成测试。因为我们实际上也在运行FastAPI代码。 我认为,第二个选择更接近单元测试定义的选择是直接运行该函数:
def test_read_main():
response = read_main()
assert response == {"msg": "Hello World"}
同样,在Django中,我们可以直接调用视图功能,也可以使用客户端对象。 我的第一个问题是哪个更好?
假设我们选择了其中之一,现在为了防止调用数据库,我嘲笑了数据库。现在,我想测试只需检查数据库中是否存在某些内容的视图。我的第二个问题是测试这种观点的意义是什么?因为嘲笑数据库后,我们知道用给定参数调用数据库时会发生什么。
Let's say I have a Fastapi application like this (This code is taken from documentations):
app = FastAPI()
@app.get("/foo")
async def read_main():
return {"msg": "Hello World"}
I believe there are two ways of testing this view. The first one is by the use of a client object. For instance:
client = TestClient(app)
def test_read_main():
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"msg": "Hello World"}
However, I think this is not a unit test. It is more like an integration test. Because we are actually running fastapi codes as well.
The second option which in my opinion is closer to unit test definition is to run the function directly:
def test_read_main():
response = read_main()
assert response == {"msg": "Hello World"}
Similarly, in Django, we can directly call the view function, or by using a client object.
My first question is which one is better?
Let's say we chose one of them and now in order to prevent calling the database I have mocked the database. Now I want to test a view that just checks if something exists in the database. My second question is what is the point of testing such view? Becuase after mocking the database, we know what would happen when calling the database with given arguments.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论