我正在尝试使用自定义注释来为我正在其中实现一些 Spring AOP 方面的 Spring MVC 应用程序设置测试环境。该设置涉及一些 Spring 注释,因此我试图将它们压缩为一个。我能够获得注释来表明它不会在编译时引发错误,但是当我尝试在测试用例中使用它时,它没有任何效果。
这是注释本身。
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:无法在 null 对象上调用方法 getListOfStoresThisUserCanUse()
。这让我认为测试没有使用 application-context.xml,因此它找不到将它们注入(inject)到我的测试用例中所需的 bean。
我进行了谷歌搜索,发现了一些我丢失的部分(@Retention
和 @Target
),但即使所有内容似乎都写得正确,我无法让它工作。
是的,这就是我所做的一切。有人告诉我,我不需要对应用程序中的 web.xml 或 application-context.xml 文件进行任何修改,所以......希望这是正确的。我宁愿远离编写 XML bean,因为它与我们的一般设计模式不一致。 Buuuuut,如果我必须这样做,我就必须这样做。因此,如果有人能回答这个问题,那就太好了。
最佳答案
我不确定您正在尝试做的事情(创建元注释)在 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 {
}
关于java - 无法在 Spring 中获取自定义注释以在 Spock 集成测试中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22822577/