您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Spring Aspect没有在单元测试中触发

Spring Aspect没有在单元测试中触发

好的..所以解决方案最终是由您自己提出的..您猜对了..阅??读文档:/

http://docs.spring.io/spring-framework/docs/3.2.0.BUILD- SNAPSHOT/reference/htmlsingle/#spring-mvc-test- framework

此外,您可以通过Spring配置将模拟服务注入到控制器中,以便专注于测试Web层。

因此,最终的解决方案如下所示:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {"testContext.xml","../path/to/applicationContext.xml"})
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class})
public class MyControllerTest {

    private mockmvc mockmvc;

    @Autowired
    private WebApplicationContext wac;

    @Autowired
    private MyService myService;

    @Before
    public void setup() {
        this.mockmvc = mockmvcBuilders.webAppContextSetup(wac).build();
    }

    @Test
    public void mytest() {
        MyRequest request = new MyRequest();
        MyResponse response = new MyResponse();
        String expectedValue = "foobar";

        Mockito.when(myService.doSomething((MyRequest) Mockito.any())).thenReturn(response);

        MockHttpServletRequestBuilder builder = mockmvcRequestBuilders.post("/myendpoint");

        String request = IoUtils.toString(context.getResource("classpath:/request.json").getURI());

        builder.content(request);
        builder.contentType(MediaType.APPLICATION_JSON);

        mockmvc.perform(builder)
                .andExpect(mockmvcResultMatchers.status().isOk())
                .andExpect(mockmvcResultMatchers.jsonPath("$.someKey").value(expectedValue));

        Mockito.verify(myService, Mockito.times(1)).doSomething((MyRequest) Mockito.any());
    }
}

然后,您只需为此测试定义一个上下文文件testContext.xml其中包含服务对象的模拟:

<bean id="myService" class="org.mockito.Mockito" factory-method="mock">
    <constructor-arg value="com.mypackage.MyService"/>
</bean>

重要的是,MyService实例已@Autowired进入测试,因此可以进行编排。

这允许您模拟出您喜欢的任何实例,无论它们是否在服务类,方面等中,只要您适当地命名Bean。因此,在这种情况下,MyService将声明为:

@Component("myService")
public class MyService {
...
Java 2022/1/1 18:21:20 有438人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶