【发布时间】: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