[英]Unit testing with AspectJ in Java
我正在開發一個使用AspectJ和Java的應用程序。 在開發中,我一起使用ajc和java。 AspectJ在必要時調用一些代碼段,我想測試AspectJ調用的這些代碼段。 我嘗試用Mockito做但我失敗了,有沒有人知道任何其他方法來測試它?
我不確定如何在普通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 ,也可以使用上述方法,因為我使用的方法將允許您擁有配置類(可以且應該是駐留在其自己的文件中的公共類)。
如果使用@EnableAspectJAutoProxy(proxyTargetClass = true)
注釋@Configuration
類, Spring將知道它需要在您的測試/應用程序中啟用方面。
如果您需要任何額外的說明,我會提供進一步的編輯。
編輯:
Maven Spring-Test依賴是:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
我剛剛創建了一個JUnit4 Runner,允許在JUnit測試用例上進行AspectJ加載時編織。 這是一個簡單的例子:
我創建了一個HelloService來返回問候語。 我創建了一個Aspect來在問候大寫中創建名稱。 最后,我創建了一個單元測試,以使用具有小寫名稱的HelloService並期望大寫結果。
該示例的所有細節都是GitHub項目的一部分供參考: https : //github.com/david-888/aspectj-junit-runner
只需在類路徑中包含最新的aspectj-junit-runner JAR 。 那么你的測試可能如下所示:
@AspectJConfig(classpathAdditions = "src/test/hello-resources")
@RunWith(AspectJUnit4Runner.class)
public class HelloTest {
@Test
public void getLiveGreeting() {
String expected = "Hello FRIEND!";
HelloService helloService = new HelloService();
String greeting = helloService.sayHello("friend");
Assert.assertEquals(expected, greeting);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.