Mockito上的空指针

tjvv9vkg  于 2022-11-08  发布在  其他
关注(0)|答案(3)|浏览(179)

我使用下面的测试来测试我的utiliesclass,我使用mockito来进行sql连接。

@Mock
    public Connection connectionMock;

    @Before
    public void setUp(){
        MockitoAnnotations.initMocks(this);
    }    
@Test
    public void testResource(){
        String sql = Utilities.resourceToString("testSql.sql");
        try {
            Mockito.when(connectionMock.createStatement().executeQuery(sql)).thenAnswer(new Answer<String>() {
                @Override
                public String answer(InvocationOnMock invocationOnMock) throws Throwable {
                    return "X";
                }
            });

我在Mockito行上得到了一个空指针。什么时候,什么地方出了问题?

mrwjdhj3

mrwjdhj31#

你还需要一次嘲弄...

connectionMock.createStatement()

...将返回null,除非您为其设置了预期值。
例如,添加...

@Mock
private Statement statement;

...

when(connectionMock.createStatement()).thenReturn(statement);
when(statement.executeQuery(sql)).thenAnswer(...);

更新

若要回答下面的注解,应返回结果集,而不是字符串。例如...

@Mock
private ResultSet resultSet;

...

when(statement.executeQuery(sql)).thenReturn(resultSet);
when(resultSet.getString(1)).thenReturn("X");

... call the class under the test...

// Add verification that "next" was called before "getString"...
// (not 100% necessary, but makes it a more thorough test)
InOrder order = inOrder(resultSet);
order.verify(resultSet).next();
order.verify(resultSet).getString(1);

更新#2
删除错误的内容

8yoxcaq7

8yoxcaq72#

你可以试着用RETURNS_DEEP_STUBS;
在您的程式码中,它会看起来像这样:

public Connection connectionMock;

    @Before
    public void setUp(){
        connectionMock = Mockito.mock(Connection.class, RETURNS_DEEP_STUBS);
    }

    ...
d6kp6zgx

d6kp6zgx3#

实际上,你可以有一个更好的用法关于Mockito:

@RunWith(MockitoJUnitRunner.class)
 public class ExampleTest {
     @Mock
     public Connection connectionMock;     
 }

相关问题