Java中程序的执行单元,用Java中的AspectJ进行单元测试

我不确定如何在普通Java和JUnit中执行此操作,但是如果您可以访问Spring-Integration-Test,则可以轻松使用MockMVC及其提供的支持类.

在下面,您可以看到一个示例,在该示例中,我正在测试一个控制器,其中包含一个Aspect:

@RunWith(SpringJUnit4ClassRunner.class)

@WebAppConfiguration

@ContextConfiguration

public class ControllerWithAspectTest {

@Autowired

private WebApplicationContext wac;

@Autowired

private MockMvc mockMvc;

@Autowired

@InjectMocks

private MongoController mongoController;

@Before

public void setup() {

this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();

// if you want to inject mocks into your controller

MockitoAnnotations.initMocks(this);

}

@Test

public void testControllerWithAspect() throws Exception {

MvcResult result = mockMvc

.perform(

MockMvcRequestBuilders.get("/my/get/url")

.contentType(MediaType.APPLICATION_JSON)

.accept(MediaType.APPLICATION_JSON))

.andExpect(MockMvcResultMatchers.status().isOk()).andReturn();

}

@Configuration

@EnableWebMvc

@EnableAspectJAutoProxy(proxyTargetClass = true)

static class Config extends WebMvcConfigurerAdapter {

@Bean

public MongoAuditingAspect getAuditingAspect() {

return new MongoAuditingAspect();

}

}

}

即使您没有在应用程序中配置Spring,也可以使用上面的方法,因为我使用的方法将允许您有一个配置类(可以并且应该是驻留在其自己文件中的公共类).

而且,如果@Configuration类使用@EnableAspectJAutoProxy(proxyTargetClass = true)进行注释,则Spring将知道它需要启用测试/应用程序中的各个方面.

如果您需要任何其他说明,我将对其进行进一步的编辑.

编辑:

Maven Spring-Test依赖项是:

org.springframework

spring-test

${spring.version}

test

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值