【发布时间】:2016-12-20 11:21:17
【问题描述】:
我试图存根假设由特定服务方法返回到控制器中存在的方法的一组数据,因此我需要存根三个方法调用(getLopaReConfigPath、getBASeatKit 和 getBAColumnSeatKit),它仅适用于一个方法并且不适用于其他方法!!!
下面是要测试的Controller方法的代码
@RequestMapping(value = "/getSeatLayoutDisplay", method = RequestMethod.POST)
@ResponseBody JSONObject getSeatLayoutDisplay(@RequestBody String params) {
JSONObject resultJson = new JSONObject();
JSONObject combinedJson = new JSONObject();
try {
JsonObject gsonData = parseRequestDataToJson(params);
StringBuffer filePathBuf = new StringBuffer(commonUtil.getLopaReConfigPath(gsonData.get("carrierName").getAsString(), gsonData.get("dbName").getAsString()));
filePathBuf.append(LoadPropertyFiles.getInstance().getProperty("INPUT"));
String seatKitXmlFilePath = filePathBuf.append(LoadPropertyFiles.getInstance().getProperty("XMLS")).toString();
String columnXMl = filePathBuf.append(Constants.COLUMN_XML_FILENAME).toString();
BASeatKitInfo seatKitInfo = lopaReConfigService.getBASeatKit(seatKitXmlFilePath);
KitLayout columnSeatKitLeft = lopaReConfigService.getBAColumnSeatKit(gsonData.get("filepath").getAsString(),columnXMl);
combinedJson.put("kitLayoutCenter", columnSeatKitLeft);
combinedJson.put("kitInfo", seatKitInfo);
resultJson.put("lopaReconfig",combinedJson);
} catch (Exception e) {
logger.error(" Failed due to " + e);
}
return resultJson;
}
以下是我返回的测试用例
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=AnnotationConfigWebContextLoader.class)
@WebAppConfiguration
public class LopaReConfigControllerTest {
public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
// Application dependency
private MockMvc mvc;
@Mock
LopaReConfigService lopaReConfigService;
@Mock
CommonUtil commonUtil;
@Mock
ProcessLopaReconfigFile processLopaReconfigFile;
@Mock
DBImportRepository dbImportRepository;
@InjectMocks
MockHttpSession session;
@Autowired
WebApplicationContext context;
@InjectMocks
LopaReConfigController lopaReConfigController;
@Mock
UserSessionPool sessionPool;
@Before
public void setup() {
// Process mock annotations
MockitoAnnotations.initMocks(this);
this.mvc = MockMvcBuilders.standaloneSetup(lopaReConfigController).build();
}
@Test
public void test_getSeatLayoutDisplay() throws Exception {
// Construct JSON data to pass as parameter
BASeatkitDataFeeder seatKitDataFeeder = new BASeatkitDataFeeder();
Gson gson = new Gson();
CommonUtil util = new CommonUtil();
StringBuffer filePathBuff = new StringBuffer();
filePathBuff.append(util.getLopaReConfigPath("ABC-300ER", "ABC-300ER-B777-v300B"));
filePathBuff.append(LoadPropertyFiles.getInstance().getProperty("INPUT"));
seatKitDataFeeder.setBuildVersion("Base");
seatKitDataFeeder.setCarrierName("ABC-300ER");
seatKitDataFeeder.setDbId("1558");
seatKitDataFeeder.setDbName("ABC-300ER-B777-v300B");
seatKitDataFeeder.setSessionId(session.getId());
seatKitDataFeeder.setFilepath(filePathBuff.toString());
String seatKitXmlFilePath = filePathBuff.append(LoadPropertyFiles.getInstance().getProperty("XMLS")).toString();
String columnXMl = filePathBuff.append(Constants.COLUMN_XML_FILENAME).toString();
LopaReConfigRepositoryImpl lopaImpl = new LopaReConfigRepositoryImpl();
BASeatKitInfo BAinfo = lopaImpl.getBASeatKit(seatKitXmlFilePath);
KitLayout kitLayout = lopaImpl.getBAColumnSeatKit(seatKitXmlFilePath+Constants.SEATKIT_COLUMN_XML_FILENAME,columnXMl);
//Stub the result whaen methods get called
Mockito.when(commonUtil.getLopaReConfigPath("ABC-300ER", "ABC-300ER-B777-v300B")).thenReturn(filePathBuff.toString()); // working fine
Mockito.when(lopaReConfigService.getBASeatKit(seatKitXmlFilePath)).thenReturn(BAinfo); // not stubbing the BAinfo object when method is called
Mockito.when(lopaReConfigService.getBAColumnSeatKit("","")).thenReturn(kitLayout); // not stubbing the kitLayout object when method is called
// Test method logic
mvc.perform(post("/getSeatLayoutDisplay")
.contentType(MediaType.APPLICATION_JSON).content(jsonStub))
.andExpect(status().isOk()) // After hitting specific URL/URI check the status code fall under 200 series
.andExpect(content().contentType(APPLICATION_JSON_UTF8)); // Check the return statement is JSON
// Verify that the the lopaReConfigService is called only once during execution.
verify(lopaReConfigService, times(0)).getBASeatKit(seatKitXmlFilePath);
verify(lopaReConfigService, times(0)).getBAColumnSeatKit(seatKitDataFeeder.getFilepath(),columnXMl);
}
}
问题是我试图为 3 种方法存根对象,但 mockito 在第一个方法被调用时正确设置了结果,但其他两种方法没有发生同样的事情
我尝试过使用 Matcher 并覆盖 equals 和 hashcode 方法,但它仍然没有帮助我。
任何帮助将不胜感激。
使用以下方法可以正常工作
Mockito.when(commonUtil.getLopaReConfigPath("ABC-300ER", "ABC-300ER-B777-v300B")).thenReturn(filePathBuff.toString()); // working fine
不适用于以下方法
Mockito.when(lopaReConfigService.getBASeatKit(seatKitXmlFilePath)).thenReturn(BAinfo); // not stubbing the BAinfo object when method is called
Mockito.when(lopaReConfigService.getBAColumnSeatKit("","")).thenReturn(kitLayout); // not stubbing the kitLayout object when method is called
【问题讨论】:
-
您遇到的错误是什么?也发布堆栈跟踪。
-
Jobin 我没有收到任何错误,当控制器调用服务方法返回空值时
-
这是返回有效输出
lopaImpl.getBASeatKit(seatKitXmlFilePath);吗? -
我使用 Mockito.when 来存根假设在实际执行该方法时由服务层方法提供的数据,听说我只是想模拟它来测试存在的代码部分在控制器中
-
你在写什么样的测试是单元测试还是集成测试?
lopaImpl.getBASeatKit(seatKitXmlFilePath);在测试中的价值是什么?
标签: spring-mvc junit mockito