【问题标题】:DAO object not getting mocked in Service Layer using Junit 5 and Mockito使用 Junit 5 和 Mockito 在服务层中未模拟 DAO 对象
【发布时间】:2022-11-11 02:56:42
【问题描述】:

我正在使用 JUnit 5 和 Mockito 为服务层编写测试用例。我正在使用@Mock 模拟数据库层并使用@InjectMocks 注入服务层。但是,当调用到服务方法时,来自 DAO 的模拟列表以某种方式变为空。我为其他测试类设置了类似的设置,并且运行良好。我什至通过创建一个接受字符串参数并返回字符串对象的简单流程来尝试在同一个类中并且它起作用了。但不知何故,这种方法对我不起作用。在调试时,我检查了参数是否按预期传递,它只是 DAO 层即使在模拟后也给出了空列表。请让我知道我在这里做错了什么。

服务层

@Service
public class XyzServiceImpl implements XyzService {

    @Autowired
    private XyzDAO xyzDAO;

   @Override
    public Map<String, String> getRecords(Map<String, String> allParams) throws Exception {
        
        String key = allParams.get("key");
        String configValue = System.getProperty(key);
        
        XyzRoot xyzRoot = new ObjectMapper().readValue(configValue, XyzRoot.class);
        List<Map<String, Object>> records = xyzDao.getRecords(xyzRoot, allParams); // list is coming as empty

        
        for (Entry<String, Object> entry : records.get(0).entrySet()) { 
            recordsMap.put(entry.getKey(), entry.getValue()!= null ? entry.getValue().toString() : "");
        }
        
        return recordsMap;
    }
}

这是测试类的代码

public class TestXyzService {
    
    @InjectMocks
    private XyzServiceImpl xyzServiceImpl;

    @Mock
    private xyzDAO xyzDao;

    private static String data = null;

    @BeforeEach
    public void init() {
        MockitoAnnotations.initMocks(this);
    }

    @BeforeAll
    public static void setUp() throws IOException {
        data = FileUtils.loadFileData("record-history.json");
    }
    

    @Test
    void getRecordTest() throws Exception {

        Gson gson = new Gson();

        Map<String, String> expectedDetails = gson.fromJson(data,
                new TypeToken<Map<String, String>>() {
                }.getType());
        Map<String, Object> recordDetailsMap = gson.fromJson(data,
                new TypeToken<Map<String, Object>>() {
                }.getType());

        List<Map<String, Object>> recordDetails = new ArrayList<>();
        recordDetails.add(recordDetailsMap);

        Map<String, String> allParams = new LinkedHashMap<>();
        allParams.put(AppConstants.PARAM_PAGE_NAME, "HISTORY_TBL");
        allParams.put(AppConstants.PARAM_ARG1, AppConstants.ARG1);

        XyzRoot xyzRoot = new XyzRoot();
        xyzRoot.setTable("TEST_TBL");

        Configuration configuration = new Configuration();
        configuration.setArgument("COL");

        xyzRoot.setConfig(configuration);

        String config = gson.toJson(xyzRoot);

        System.setProperty("key", config);

        when(xyzDao.getRecords(xyzRoot, allParams)).thenReturn(recordDetails);

        Map<String, String> actualDetails = xyzServiceImpl.getRecords(allParams); // getting error due to empty list from dao

        assertNotNull(actualDetails);
        assertEquals(expectedDetails, actualDetails);
        verify(xyzDaoDao, times(1)).getRecords(xyzRoot, allParams);
    }
}

【问题讨论】:

  • 听起来很明显,但是您是否检查过您的模拟响应是否已在测试中填充
  • XyzRoot 是否实现 equals 和 hashCode 方法?如果是,请提供代码。
  • @johnnyutts 是的。如果我尝试使用 dao 调用代替服务调用,则会出现模拟响应。
  • @Jonasz 不,它没有实现 equals 和 hashcode

标签: java spring-boot unit-testing mockito junit5


【解决方案1】:

ObjectMapper 在这一行创建的对象:

XyzRoot xyzRoot = new ObjectMapper().readValue(configValue, XyzRoot.class);

是一个与您在测试中创建的实例完全分离的实例:

XyzRoot xyzRoot = new XyzRoot();
xyzRoot.setTable("TEST_TBL");

您没有为XyzRoot 实现equals 方法,所以简单的引用相等验证(==),这是所有类继承的默认Object 实现,返回false,因为对象是两个完全独立的实例。这就是为什么你的测试中定义的when(...).thenReturn(...) 不能正常工作的原因——当 Mockito 检查它是否应该为给定的对象触发时,it uses equals method by default。

要解决此问题,您应该执行以下操作之一:

【讨论】:

  • 感谢您的详细解释。这帮助我解决了我的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-22
  • 1970-01-01
  • 2012-01-25
  • 2021-07-12
  • 1970-01-01
相关资源
最近更新 更多