调用服务类方法时,Mockito存根不起作用

时间:2016-12-20 11:21:17

标签: spring-mvc junit mockito

我试图将一组数据存根,假设是通过特定的服务方法返回到控制器中存在的方法,所以我需要存根三个方法调用(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方法,但它仍然没有帮助我。

任何帮助将不胜感激。

使用以下方法

可以正常使用Stubbing
 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

1 个答案:

答案 0 :(得分:0)

当你在代码和测试代码中使用相同的参数时,你不会提供它。

测试中的

seatKitXmlFilePath与测试代码中的

不同

你做的测试

StringBuffer filePathBuff = new StringBuffer();
filePathBuff.append(LoadPropertyFiles.getInstance().getProperty("XMLS")).toString();
String seatKitXmlFilePath = filePathBuff.append(LoadPropertyFiles.getInstance().getProperty("XMLS")).toString();

在测试代码中

StringBuffer filePathBuf = new StringBuffer(commonUtil.getLopaReConfigPath(gsonData.get("carrierName").getAsString(), gsonData.get("dbName").getAsString()));
filePathBuf.append(LoadPropertyFiles.getInstance().getProperty("XMLS")).toString();
String seatKitXmlFilePath = filePathBuf.append(LoadPropertyFiles.getInstance().getProperty("XMLS")).toString();

如果你需要它来匹配任何东西只需使用anyString()

它将匹配任何字符串

所以你的测试代码可以有

Mockito.when(lopaReConfigService.getBASeatKit(anyString())).thenReturn(BAinfo); // not stubbing the BAinfo object when method is called
        Mockito.when(lopaReConfigService.getBAColumnSeatKit(anyString(),anyString())).thenReturn(kitLayout);

并且在这种情况下它应匹配