Spring 如何配置@ContextConfiguration?
我正在尝试设置和测试我的数据库。 我需要配置@ContextConfiguration。 现在它只给我一个错误消息error:org.springframework.test.context.TestContextManager-允许TestExecutionListener[org.springframework.test.context.web时捕获异常。ServletTestExecutionListener@11739d]准备测试实例[se.lowdin.civilforsvaret.test.db]。dbTest@1bd56d0] java.lang.IllegalStateException:未能加载ApplicationContext 这很可能是因为@ContextConfiguration中的路径错误。 我测试了在那里编写classpath:/WEB-INF/Spring/root-context.xml 但这也行不通。 我怎么知道Spring 如何配置@ContextConfiguration?,spring,spring-mvc,Spring,Spring Mvc,我正在尝试设置和测试我的数据库。 我需要配置@ContextConfiguration。 现在它只给我一个错误消息error:org.springframework.test.context.TestContextManager-允许TestExecutionListener[org.springframework.test.context.web时捕获异常。ServletTestExecutionListener@11739d]准备测试实例[se.lowdin.civilforsvaret.t
import static org.junit.Assert.*;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.junit.runner.RunWith;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import se.lowdin.civilforsvaret.webapp.domain.Person;
import se.lowdin.civilforsvaret.webapp.repositories.PersonRepository;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:/WEB-INF/Spring/root-context.xml")
public class dbTest {
@Autowired
PersonRepository repo;
@Test
public void testDB() {
Person person = new Person();
person.setFirstName("Bengt");
person.setLastName("Larsson");
repo.createPerson(person);
Person dbPerson = repo.getPerson(person.getId());
assertNotNull(dbPerson);
}
}
WEB-INF目录不在类路径上,因此您不能像这样访问xml文件:
@ContextConfiguration(locations = "classpath:/WEB-INF/Spring/root-context.xml")
@ContextConfiguration(locations = "classpath:root-context.xml")
@ContextConfiguration(locations = "classpath:root-context.xml")
/WEB-INF/classes位于类路径上,因此您可以将其放在那里并按如下方式访问:
@ContextConfiguration(locations = "classpath:/WEB-INF/Spring/root-context.xml")
@ContextConfiguration(locations = "classpath:root-context.xml")
@ContextConfiguration(locations = "classpath:root-context.xml")
如果您使用的是Maven,我建议您为测试创建另一个上下文文件,并将其放入src/test/resources中。src/main/resource目录下的所有文件都被视为类路径。因此,只需将root-context.xml文件复制到资源目录中,然后在dbTest类中修改@ContextConfiguration,如下所示:
@ContextConfiguration(locations = "classpath:/WEB-INF/Spring/root-context.xml")
@ContextConfiguration(locations = "classpath:root-context.xml")
@ContextConfiguration(locations = "classpath:root-context.xml")
希望它对你有用 好的,可能是这样,但是类路径到底是什么呢?这可能有助于您了解web应用程序的类路径。