如何使用jmockit模拟公共无效方法? [英] How to mock public void method using jmockit?
问题描述
我正在尝试为Spring MVC控制器编写一些junit测试,到目前为止,我已经能够成功完成它.我也在和jmockit一起使用Spring Mock.
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.
下面是我在 DataController
控制器中的方法-
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
}
现在 SomeOtherClass
中的 processTask
方法是这样的-
Now in SomeOtherClass
, processTask
method is like this -
public void processTask(String value, List<Map<String, String>> mappings) throws Exception {
// some code here
}
下面是我为 DataController
类中的 processWork
方法编写的junit测试.
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());
}
问题陈述:-
现在的问题是,每当我运行 test03_processWork
单元测试时,它都会进入控制器的 processWork
方法(很好),然后调用<我的 SomeOtherClass
的code> processTask 方法,这就是我要避免的事情.
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.
意味着,有什么办法,我可以模拟 SomeOtherClass
的 processTask
方法以返回一些默认值,而不是运行实际的代码,方法?
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?
当前在我的junit测试运行中,它还在调用 SomeOtherClass
的 processTask
方法,并且 processTask
内部的代码也正在运行,这就是我想避免.我不希望通过使用jmockit进行模拟来运行 processTask
中的任何代码?
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?
这可能吗?
推荐答案
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 it above the mock at the starting of your unit test.
这篇关于如何使用jmockit模拟公共无效方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!