在模拟对象中获取空值

时间:2018-07-13 12:16:17

标签: java unit-testing mocking mockito

我正在尝试模拟junit测试文件中的对象。我在测试文件中获得了价值

public void TestMethod() throws SQLException{

    String projectID    =   "Test";
    Connection connectionMock = Mockito.mock(Connection.class);
    PreparedStatement preparedStatementMock = Mockito.mock(PreparedStatement.class);
    ResultSet resultSetMock = Mockito.mock(ResultSet.class);
    mockStatic(Manager.class);
    Worker  workerMock  =   Mockito.mock(Worker.class);
    mockingDetails(workerMock);
    mock(PreparedStatement.class);
    mock(ResultSet.class);
    when(workerMock.getProjectId())
    .thenReturn(projectID);

    when(Manager.getDatabaseConnection())
    .thenReturn(connectionMock);

    when(connectionMock.prepareStatement(""))
    .thenReturn(preparedStatementMock);

    when(preparedStatementMock.executeQuery())
    .thenReturn(resultSetMock);
    //mockStatic(Manager.class);
    System.out.println("workerMock--------->"+workerMock);
    System.out.println("prepared stmt--------->"+preparedStatementMock);
    assertNotNull(service.getProtocol());
}

如果我在这里打印,我将成为价值工作者并准备了类似于此值的声明

  

“模拟工人,哈希码:853323835”

如果我用真实的方法打印相同的内容,则对于worker和prepared语句都将为空。我使用了注释

@RunWith(PowerMockRunner.class)
@PrepareForTest(Manager.class)

在测试课中

public String Method() throws SQLException
{
    Connection conn =   Manager.getDatabaseConnection();
    String  protocol    =   null;
    StringBuilder   qryBuilder  =   new StringBuilder("MyQuery");
    qryBuilder.append("condition = ?");
    System.out.println("worker.getProjectId()------------->"+worker);
    System.out.println("connection------------->"+conn);
    PreparedStatement pst = conn.prepareStatement(qryBuilder.toString());
    System.out.println("pst------------->"+pst);
    pst.setString(1, worker.getProjectId());
    try {
        ResultSet rset = pst.executeQuery();
        try {
            while (rset.next()) {
                protocol    =   rset.getString(1);
            }
            rset.close();
        } finally {
            pst.close();
        }
    } catch (SQLException e) {
        throw e;
    }
    return protocol;
}

0 个答案:

没有答案