调用Springs服务方法

调用Springs服务方法

本文介绍了如何从控制器(Junit)调用Springs服务方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过示例,如何使用Mockito调用spring控制器.

I have seen example , how to call spring controller using mockito.

使用Mock我称之为Spring MVC控制器.控制器调用Spring服务类.

Using Mock I call Spring MVC controller.Controller Invokes Spring service class.

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/spring/root-context.xml" })
public class TestController {


    @Mock
    private TestService testService;

    @InjectMocks
    private PaymentTransactionController paymentController;

    private MockMvc mockMvc;


     @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        this.setMockMvc(MockMvcBuilders.standaloneSetup(paymentController).build());
    }

    @Test
    public void test() throws Exception {
        this.mockMvc.perform(post("/tr/test").content(...)).andExpect(status().isOk());
        // testService.save(); <-- another way
    }

好的,效果很好.我很好地称呼我的Spring控制器.但是在Spring控制器中,我已经注入了服务层.

Ok it works well. I calls my Spring controller very well. But In Spring controller I have Injected Service Layer.

@Autowired
private TestService serviceTest;


@RequestMapping(value = "/test", method = RequestMethod.POST)
@ResponseBody()
public String test(HttpServletRequest request) {
   ...
    serviceTest.save();
   // in save method I call dao and dao perist data;
   // I have injected dao intrface in serviceTest layer
   ...
   return result;

}

问题在于,我的应用程序未调用save方法,未在其中输入.我也没有错误.同样的结果是当我从Junit调用save()方法时(我已经在test()方法中对其进行了注释).

The problem is that, my app does not invokes save method, it is not entered in it. I have no error too. The same result is when I call save() method from Junit (I have commented it in test() method).

当我调试时,我看到org.mockito.internal.creation.MethodInterceptorFilter发生了中断方法

When I debug, I have seen that interrupt method happens of org.mockito.internal.creation.MethodInterceptorFilter

如何解决这个问题?会发生什么?

How to solve this problem? what happens?

推荐答案

只需将@InjectMocks更改为@Autowired.这样就解决了问题!在这种情况下,您不是在模拟,而是在使用真实数据调用方法.

just change @InjectMocks to @Autowired. This fix the issue! In this case you are not mocking, you are invoking method with real data.

这篇关于如何从控制器(Junit)调用Springs服务方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 20:42