我正在使用python mock。补丁,并希望更改每个调用的返回值。 以下是警告: 被修补的函数没有输入,所以我不能根据输入改变返回值。

下面是我的代码供参考。

def get_boolean_response():
    response = io.prompt('y/n').lower()
    while response not in ('y', 'n', 'yes', 'no'):
        io.echo('Not a valid input. Try again'])
        response = io.prompt('y/n').lower()

    return response in ('y', 'yes')

我的测试代码:

@mock.patch('io')
def test_get_boolean_response(self, mock_io):
    #setup
    mock_io.prompt.return_value = ['x','y']
    result = operations.get_boolean_response()

    #test
    self.assertTrue(result)
    self.assertEqual(mock_io.prompt.call_count, 2)

io。提示符只是一个平台独立(python 2和3)版本的“输入”。最终我要模拟出用户的输入。我已经尝试使用一个列表的返回值,但这并不接缝工作。

你可以看到,如果返回值是无效的,我就会得到一个无限循环。所以我需要一种最终改变返回值的方法,这样我的测试才能真正完成。

(回答这个问题的另一种可能的方式是解释我如何在单元测试中模拟用户输入)


没有这个问题,主要是因为我没有能力改变输入。

关于这个问题的回答的其中一个评论是沿着同样的路线,但没有提供答案/评论。

我有一个方法调用,我想用mockito模拟。首先,我已经创建并注入了一个对象的实例,该方法将在其上被调用。我的目的是验证方法调用中的一个对象。

是否有一种方法,mockito允许您断言或验证对象和它的属性时,mock方法被调用?

例子

Mockito.verify(mockedObject)
       .someMethodOnMockedObject(
              Mockito.<SomeObjectAsArgument>anyObject())

而不是做anyObject()我想检查参数对象包含一些特定的字段

Mockito.verify(mockedObject)
       .someMethodOnMockedObject(
              Mockito.<SomeObjectAsArgument>**compareWithThisObject()**)

我试图测试一些遗留代码,使用Mockito。

我想存根在生产中使用的FooDao如下:

foo = fooDao.getBar(new Bazoo());

我可以这样写:

when(fooDao.getBar(new Bazoo())).thenReturn(myFoo);

但明显的问题是,getBar()从未使用我为该方法存根的同一个Bazoo对象调用。(该死的新接线员!)

如果我能以一种不管参数如何返回myFoo的方式存根这个方法,我会很高兴。如果做不到这一点,我将听取其他解决方案的建议,但我真的希望在有合理的测试覆盖率之前避免更改生产代码。

用Java创建模拟对象的最佳框架是什么?为什么?每个框架的优点和缺点是什么?

我有简单的积分测试

@Test
public void shouldReturnErrorMessageToAdminWhenCreatingUserWithUsedUserName() throws Exception {
    mockMvc.perform(post("/api/users").header("Authorization", base64ForTestUser).contentType(MediaType.APPLICATION_JSON)
        .content("{\"userName\":\"testUserDetails\",\"firstName\":\"xxx\",\"lastName\":\"xxx\",\"password\":\"xxx\"}"))
        .andDo(print())
        .andExpect(status().isBadRequest())
        .andExpect(?);
}

在最后一行中,我想比较在响应体中接收到的字符串与预期的字符串

我得到的回答是:

MockHttpServletResponse:
          Status = 400
   Error message = null
         Headers = {Content-Type=[application/json]}
    Content type = application/json
            Body = "Username already taken"
   Forwarded URL = null
  Redirected URL = null

尝试了content(), body()的一些技巧,但都不起作用。

我试图使用python模拟包来模拟python请求模块。让我在下面的场景中工作的基本调用是什么?

在views.py中,我有一个函数,它每次都以不同的响应进行各种request .get()调用

def myview(request):
  res1 = requests.get('aurl')
  res2 = request.get('burl')
  res3 = request.get('curl')

在我的测试类中,我想做类似的事情,但不能确定确切的方法调用

步骤1:

# Mock the requests module
# when mockedRequests.get('aurl') is called then return 'a response'
# when mockedRequests.get('burl') is called then return 'b response'
# when mockedRequests.get('curl') is called then return 'c response'

步骤2:

调用我的视图

步骤3:

验证响应包含'a response', 'b response', 'c response'

我如何完成第1步(模拟请求模块)?

我使用过很多web应用程序,它们都是由后台复杂程度各异的数据库驱动的。通常,有一个ORM层独立于业务和表示逻辑。这使得单元测试业务逻辑相当简单;事情可以在离散的模块中实现,测试所需的任何数据都可以通过对象模拟来伪造。

但是测试ORM和数据库本身总是充满了问题和妥协。

这些年来,我尝试了一些策略,但没有一个能让我完全满意。

Load a test database with known data. Run tests against the ORM and confirm that the right data comes back. The disadvantage here is that your test DB has to keep up with any schema changes in the application database, and might get out of sync. It also relies on artificial data, and may not expose bugs that occur due to stupid user input. Finally, if the test database is small, it won't reveal inefficiencies like a missing index. (OK, that last one isn't really what unit testing should be used for, but it doesn't hurt.) Load a copy of the production database and test against that. The problem here is that you may have no idea what's in the production DB at any given time; your tests may need to be rewritten if data changes over time.

有些人指出,这两种策略都依赖于特定的数据,单元测试应该只测试功能。为此,我看到了一些建议:

使用模拟数据库服务器,只检查ORM是否在响应给定方法调用时发送了正确的查询。

您在测试数据库驱动的应用程序时使用了哪些策略?对你来说最有效的方法是什么?

是否有一种方法可以让存根方法在后续调用时返回不同的对象?我希望这样做是为了测试来自ExecutorCompletionService的不确定响应。也就是说,测试不管方法的返回顺序如何,结果都保持不变。

我要测试的代码看起来像这样。

// Create an completion service so we can group these tasks together
ExecutorCompletionService<T> completionService =
        new ExecutorCompletionService<T>(service);

// Add all these tasks to the completion service
for (Callable<T> t : ts)
    completionService.submit(request);

// As an when each call finished, add it to the response set.
for (int i = 0; i < calls.size(); i ++) {
    try {
        T t = completionService.take().get();
        // do some stuff that I want to test
    } catch (...) { }        
}

我想测试我的一个ES6模块以特定的方式调用另一个ES6模块。对贾斯敏来说,这非常简单

应用程序代码:

// myModule.js
import dependency from './dependency';

export default (x) => {
  dependency.doSomething(x * 2);
}

测试代码:

//myModule-test.js
import myModule from '../myModule';
import dependency from '../dependency';

describe('myModule', () => {
  it('calls the dependency with double the input', () => {
    spyOn(dependency, 'doSomething');

    myModule(2);

    expect(dependency.doSomething).toHaveBeenCalledWith(4);
  });
});

与Jest对应的是什么?我觉得这是一件很简单的事情,但我一直在努力想弄清楚。

我最接近的方法是用require替换导入,并将它们移动到测试/函数中。这两件事我都不想做。

// myModule.js
export default (x) => {
  const dependency = require('./dependency'); // Yuck
  dependency.doSomething(x * 2);
}

//myModule-test.js
describe('myModule', () => {
  it('calls the dependency with double the input', () => {
    jest.mock('../dependency');

    myModule(2);

    const dependency = require('../dependency'); // Also yuck
    expect(dependency.doSomething).toBeCalledWith(4);
  });
});

作为奖励,我希望在dependency.js中的函数是默认导出时使整个事情正常工作。但是,我知道监视默认导出在Jasmine中不起作用(或者至少我永远无法让它起作用),所以我对在Jest中也能做到这一点不抱希望。

我写了一个工厂来产生java.sql.Connection对象:

public class MySQLDatabaseConnectionFactory implements DatabaseConnectionFactory {

    @Override public Connection getConnection() {
        try {
            return DriverManager.getConnection(...);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

我想验证传递给DriverManager的参数。getConnection,但我不知道如何模拟静态方法。我的测试用例使用JUnit 4和Mockito。是否有一个好的方法来模拟/验证这个特定的用例?