我看过例子,如何使用 mockito 调用 spring 控制器。
使用 Mock 我调用 Spring MVC 控制器。控制器调用 Spring 服务类。
@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 控制器中,我已经注入了服务层。
@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;
}
问题是,我的应用程序没有调用保存方法,它没有被输入。我也没有错误。当我从 Junit 调用 save() 方法时,结果相同(我在 test() 方法中对其进行了注释)。
当我调试时,我看到 org.mockito.internal.creation.MethodInterceptorFilter 发生了中断方法
如何解决这个问题呢?发生什么了?