【问题标题】:what is the correct way to make mocks when testing a method?测试方法时制作模拟的正确方法是什么?
【发布时间】:2015-05-21 22:20:40
【问题描述】:

我是新手,特别是 jMock(对于 java)。我之前做过一些测试,但没有使用 mock,我想知道制作它们的正确方法是什么。

例如,我有一个带有实现的服务.. 所以,我有这个服务测试。在服务器测试中,我有我的方法。

假设我在serviceHelperTest 上有methodA,作为methodA 的一部分,我有这个

ArrayList someValues = serviceHelperImpl.otherMethod

所以,据我所知,我应该模拟这个serviceHelperImpl.othermethod,因为我并不关心它是否好,它应该返回一些值。

那么,假设我期望 boolean 值,是否可以这样做?

public myMethodToTest(){
     mockery.checking(new Expectations() {
     {
                oneOf(serviceHelper).otherMethod();
                will(returnValue(true));


            }
        });


     Boolean myVar = serviceHelper.otherMethod();
     ...
}

我不知道这是否正确...知道如何在测试单元上实现模拟吗?

【问题讨论】:

  • 您的解释令人困惑。 methodA 或 serviceHelperImpl 在哪里?你能展示一个完整的例子吗
  • 我不确定您是在问练习问题(应该如何使用模拟)还是实施问题(在这种情况下如何使用模拟)。如果是前者,也许看看michaelminella.com/testing/the-concept-of-mocking.html。如果是后者,那么您将需要提出更具体的问题并接受答案会根据模拟框架而改变。

标签: java unit-testing mocking


【解决方案1】:

我不太确定你为什么要尝试从serviceHelper.otherMethod(); 保存返回值,如果这样做的目的是测试otherMethod,你应该只调用serviceHelper.otherMethod();,而不将返回值保存在变量中。请记住,模拟测试是检查函数的“状态”,而不是结果。如果你想检查结果,你应该使用 xUnit 测试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-04
    • 2019-01-12
    相关资源
    最近更新 更多