当一个方法应该在测试用例中被模拟时,可以@mock.patch
在 pythonunittest
框架中应用装饰器(参见1):
class MyTest(TestCase):
@patch('method2')
@patch('method1')
def test_stuff(self, mock_method1, mock_method_2):
...
Run Code Online (Sandbox Code Playgroud)
根据文档2,也可以将 用作@mock.patch
类装饰器:
@patch('method2')
@patch('method1')
class MyTest(TestCase):
def test_stuff(self, mock_method_1, mock_method_2):
...
Run Code Online (Sandbox Code Playgroud)
因此,将这两种方法结合起来也应该是可能且合理的:
@patch('method1')
class MyTest(TestCase):
@patch('method2')
def test_stuff(self, mock_method_A, mock_method_B):
...
Run Code Online (Sandbox Code Playgroud)
现在我想知道模拟按什么顺序传递给test_stuff
. 那么mock_method_A
嘲笑method1
还是method2
?
如何使用自定义模型功能来预加载选定的数据Repo.insert
?我不会在控制器中复制模型中的代码。
在帖子模型中:
def preload_all(query) do
tags = from(t in Tag, select: %{id: t.id, value: t.id})
from b in query, preload: [:user, tags: ^tags]
end
Run Code Online (Sandbox Code Playgroud)
在控制器中:
case Repo.insert(changeset) do
{:ok, post} ->
# post = post |> Post.preload_all
post = Repo.preload(post, [:user, :tags])
end
Run Code Online (Sandbox Code Playgroud)