[英]How to mock public void method using jmockit?
I am trying to write some junit test for my Spring MVC controller and so far I am able to do it successfully. 我正在尝试为我的Spring MVC控制器编写一些junit测试,到目前为止,我已经能够成功完成它。 I am using Spring Mock along with jmockit as well.
我也与jmockit一起使用Spring Mock。
Below is my method in the DataController
controller - 下面是我在
DataController
控制器中的方法-
@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 - 现在在
SomeOtherClass
, processTask
方法是这样的-
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. 以下是我为
DataController
类中的processWork
方法编写的junit测试。
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. 现在的问题是,每当我运行
test03_processWork
单元测试时,它都会进入控制器的processWork
方法(这很好),然后调用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? 意思是,有什么办法,我可以模拟
SomeOtherClass
processTask
方法来返回一些默认值,而不是运行实际的代码, 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. 当前,在我的junit测试运行中,它也正在调用
SomeOtherClass
processTask
方法,并且processTask
的代码也正在运行,这就是我要避免的事情。 I don't want any of the code which is there in processTask
to run by mocking using jmockit? 我不希望使用jmockit通过模拟运行
processTask
存在的任何代码?
Is this possible to do? 这可能吗?
You can use JMockit to mock your public void
method like this: 您可以使用JMockit来模拟您的
public void
方法,如下所示:
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. 只需在单元测试开始时将其添加到模拟上方即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.