ECM
ECM
总版主
总版主
  • 社区居民
  • 忠实会员
  • 原创写手
阅读:655回复:0

How to mock public void method using jmockit?

楼主#
更多 发布于:2016-05-12 14:42
I am trying to write some junit test for my Spring MVC controller and so far I am able to do it successfully. I am using Spring Mock along with jmockit as well. Below is my method in the DataController controller - @RequestMapping(value = "processWork", method = RequestMethod.GET)
public @ResponseBody
DataResponse processWork(@RequestParam("conf") final String value, @RequestParam("dc") final String dc) {

    // .. some code here


    SomeOtherClass modifier = new SomeOtherClass(zookClient);
    List<Map<String, String>> mappings = getMappings(dc);
    modifier.processTask(value, mappings);      

    // .. some code here

}
 Now in SomeOtherClass, processTask method is like this - public void processTask(String value, List<Map<String, String>> mappings) throws Exception {

    //  some code here

}
 Below is my junit test which I wrote for the processWork method in the DataController class. private MockMvc mockMvc;

@Test
public void test03_processWork() throws Exception {

    mockMvc.perform(
        get("/processWork").param("conf", "shsysysys").param("dc", "eux")).andDo(print()).andExpect(status().isOk());

}
 Problem Statement:- Now the problem with this is, whenever I am running test03_processWork unit test, it goes into processWork method of my controller (which is fine) and then it calls processTask method of my SomeOtherClass and that is what I want to avoid. Meaning, is there any way, I can mock processTask method of SomeOtherClass to return some default value, instead of running actual code what is there in processTask method? Currently with my junit test run, it is also calling processTask method of SomeOtherClass and the code inside processTask is also running and that's what I want to avoid. I don't want any of the code which is there in processTask to run by mocking using jmockit? Is this possible to do?You can use jmockit to mock your public void method like this - new MockUp<SomeOtherClass>() {
    @Mock
    public void processTask(String value, List<Map<String, String>> mappings) throws Exception {
        System.out.println("Hello World");
    }
};
 Just add above mock at the starting of your unit test.

 

 

 

 

 

 

 

异常中心网是一家专门收集整理程序员编程过程中遇到的常见异常(exception)以及各种异常问答中心的网站。异常中心网旨在,减少程序员在编码遇到异常,处理各种异常时间和痛苦,让程序员能更愉快的、快速的定位异常并查找对应的异常解决方案。异常中心网诚心打造最完美的编程社区为程序员用户服务,努力成为最好的程序员乐园程序员社区程序异常中心程序bug中心异常问答中心

 

喜欢0 评分0
游客

返回顶部