java - 通过调用数据库来 stub /模拟方法的问题

标签 java unit-testing mocking mockito

我在使用 MockitoJUnitRunner 模拟 JDBC 调用时遇到问题。 即使我在测试类中有下面的子行,Mockito 也不会以某种方式模拟实际调用。

when(readOnlyJdbcTemplate.query(anyString(), any(Object[].class), any(int[].class), any(FeatureCollectionResponseExtractor.class))).thenReturn(actual);

非常相似的模拟在另一个类中用于非常相似类型的方法。它们之间的唯一区别是我的其他类确实有 3 个参数而不是 4 个参数。下面是实际为不同类成功模拟的代码。

when(readOnlyJdbcTemplate.query(anyString(), any(Object[].class), any(FeaturesResultExtractor.class))).thenReturn(actual);

下面是我的实际代码。

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.inject.Inject;
import javax.inject.Named;
import java.net.HttpURLConnection;
import java.sql.Types;

import static com.accounts.features.utils.Constants.INTERNAL_SERVER_ERROR;

@Profile
@Log
@Named("featureLibraryDao")
public class FeatureLibraryDaoImpl implements FeatureLibraryDao {

    private static final Logger LOGGER = LogManager.getLogger(FeatureLibraryDaoImpl.class);

    @Value("${feature.library.function.sql.query}")
    private String sqlSelectQuery;

    @Inject
    @Named("readOnlyJdbcTemplate")
    private JdbcTemplate readOnlyJdbcTemplate;

    @Override
    public FeatureCollectionDTO getFeaturesData(FeatureRequest request) {
        try {
            int[] argTypes = new int[] { Types.BIGINT, Types.VARCHAR, Types.SMALLINT};
            return readOnlyJdbcTemplate.query(sqlSelectQuery, new Object[] {
                        Long.parseLong(request.getAccountId()), request.getRequestedFeatures(), request.getApplicationSuffix()
                    }, argTypes,
                    new FeatureCollectionResponseExtractor(request));
        } catch (CustomException cbe) {
            throw cbe;
        } catch (Exception ex) {
            LOGGER.error("getFeaturesData method failed with error message:{}", ex.getMessage(), ex);

            CustomErrorCode error = new CustomErrorCode(INTERNAL_SERVER_ERROR);
            error.setDeveloperText(ex.getMessage());
            throw new CustomSystemException(error, HttpURLConnection.HTTP_INTERNAL_ERROR);
        }
    }

}

下面是我的测试类。

@RunWith(MockitoJUnitRunner.class)
public class FeatureLibraryDaoImplTest {

    @InjectMocks
    private FeatureLibraryDaoImpl dao;

    @Mock
    private JdbcTemplate readOnlyJdbcTemplate;

    private List<String> features = Arrays.asList("excl_clsd_ind_only", "excl_chrgoff_ind_only", "excl_dsput_ind_only");

    @Test
    public void getFeaturesDataWhenSuccess() {
        //given
        FeatureRequest request = getFeatureRequest();
        FeatureCollectionDTO actual = new FeatureCollectionDTO(features);

        when(readOnlyJdbcTemplate.query(anyString(), any(Object[].class), any(int[].class), any(FeatureCollectionResponseExtractor.class))).thenReturn(actual);

        //when
        FeatureCollectionDTO dto = dao.getFeaturesData(request);

        //then
        assertThat(dto, notNullValue());
    }
}

关于这里有什么问题有什么建议吗? any(int[].class) 有什么问题吗?

最佳答案

我确实看到你在测试用例期间没有传递 sql 查询 sqlSelectQuery 值,但是在模拟期间你指定了 anyString() 所以它必须是一些值但不是无效的。由于您使用的是 spring 项目,您可以使用 ReflectionTestUtils 设置对象的字段值

@Before
public void setUp() {
    ReflectionTestUtils.setField(dao, "sqlSelectQuery", "query");

}

关于java - 通过调用数据库来 stub /模拟方法的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58438839/

相关文章:

java - Android Java - 取钱输出?

java - 如何为 MockMvcRequestBuilders 构建获取查询字符串?

java - 如何结合 PowerMock 和 Robolectric

python - 使用 __init__.py 模拟补丁

java - mvn jetty :run looking for a file that doesn't exist

java缓存hashmap每天过期

javascript - 我们如何使用 ember-cli 对模型混合进行单元测试

java - 作为重构之前的初始步骤,通过重写私有(private)类变量来测试方法

reactjs - 如何模拟 Firebase Auth 方法? ( react ,测试库)

unit-testing - Grails:从模拟服务返回模拟对象