我试图使用自定义注释来为Spring MVC应用程序设置我的测试环境,我将实现一些Spring AOP Aspects。设置涉及一些Spring Annotations,所以我试图将它们压缩成一个。我能够获得注释以表明它没有在编译时抛出错误,但是当我尝试在我的测试用例中使用它时,它没有任何效果。
这里是注释本身。
package com.oreillyauto.pricingweb.testingUtilities;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@ActiveProfiles("integration")
@ContextConfiguration(locations = {
"file:src/main/webapp/WEB-INF/config/application-context.xml",
"file:src/main/webapp/WEB-INF/config/AOP-context-config.xml"
})
public @interface AcitvateTestProfile {
}
基本上只是尝试将@ActivateProfiles
和@ContextConfiguration
结合起来。它至少在Eclipse中没有错误。
这是我的测试用例,用于测试我正在开发的Spring AOP实现的开始。测试是用Spock编写的,这是Groovy的一个版本,专门用于测试(对于那些不知道的人)。它使用JUNIT,非常相似......
package com.abc.efg.aspects
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.transaction.annotation.Transactional
import spock.lang.Specification
import com.abc.efg.controller.UserController
import com.abc.efg.testingUtilities.AcitvateTestProfile
@AcitvateTestProfile
@Transactional("datawhseTransactionManager")
class ControllerAspectsSpec extends Specification {
@Autowired
UserController userController
def"placeHolder"(){
given:
def returner = userController.getListOfStoresThisUserCanUse(9999)
expect:
println("Did it show up?" + returner.toString() )
}
}
我应该注意,如果我将@ActivateProfiles
和@ContextConfiguration
放在测试用例的顶部,那么测试用例就可以了。
现在,当我运行测试用例时,我给出了这样的信息:
java.lang.NullPointerException: Cannot invoke method getListOfStoresThisUserCanUse() on null object
。这让我觉得测试没有使用application-context.xml,因此它无法找到将它们注入我的测试用例所需的bean。
我已经完成了谷歌搜索并找到了我在那里丢失的一些内容(@Retention
和@Target
),但即使所有内容都写得正确,我也可以'让它工作。
是的,这就是我所做的一切。有人告诉我,我不需要对我们应用程序中的web.xml或application-context.xml文件进行任何修改,所以...希望这是正确的。我宁愿远离编写XML bean,因为它与我们的一般设计模式不一致。 Buuuuut,如果我不得不这样做。所以如果有人能说出这个问题,那也很好。
答案 0 :(得分:1)
我不确定你想要做什么(创建元注释)在Spring 4之前的Spring版本中运行良好。 在任何情况下,您都可以执行以下操作(适用于较旧的Spring版本):
@ActiveProfiles("integration")
@ContextConfiguration(locations = {
"file:src/main/webapp/WEB-INF/config/application-context.xml",
"file:src/main/webapp/WEB-INF/config/AOP-context-config.xml"
})
public abstract class AbstractSpringTest extends Specification {
}
@Transactional("datawhseTransactionManager")
public class ControllerAspectsSpec extends AbstractSpringTest {
}