Spring启动(JPA测试):执行JpaTest时无法找到@SpringBootConfiguration

时间:2017-03-24 11:57:15

标签: java spring spring-boot spring-data-jpa

我正在尝试运行一个简单的Junit测试来查看我的JpaRepository是否确实在工作。

我不断得到的错误是:

resource

我的测试班:

Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test java.lang.IllegalStateException doesn't spring boot configure itself?

我的Spring启动应用程序:

@RunWith(SpringRunner.class)
@DataJpaTest
public class LogConnectionTest {

    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private LogConnectionDao logConnectionDao;

    @Test
    public void ajouterTest() throws Exception{
        this.entityManager.persist(new LogConnection("Test",4));
        LogConnection logConnection = this.logConnectionDao.findOne((long)1);
        assertThat(logConnection.getClasseName().equals("Test"));
        assertThat(logConnection.getOriginalId() != 5);
    }
}

我的存储库:

@SpringBootApplication
public class UpsysmarocLibraryLogApplication {

    public static void main(String[] args) {
        SpringApplication.run(UpsysmarocLibraryLogApplication.class, args);
    }
}

2 个答案:

答案 0 :(得分:3)

我明白了。遵循以下惯例

1>假设您的主弹簧应用程序如下

@EnableAutoConfiguration
@SpringBootApplication
public class Application {...}

2 - ;现在创建一个可以在所有测试类中扩展的抽象类。如果你不需要这个,那么只需要使用这些配置注释并直接放入你的测试类。

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
@ActiveProfiles("test")
@WebAppConfiguration
/**
 * If you have any property file to load to test uncomment below line) 
   @TestPropertySource({
   "classpath:/properties/dbConfig-test.properties",
   "classpath:/properties/unittest.properties"
   })
*/
public abstract class AbstractSpringTest{}

然后你可以拥有你的测试类

public class LogConnectionTest extends AbstractSpringTest {

/** Instance to unit test. */
@Autowired
private LogConnectionDao logConnectionDao;

@Test
public void ajouterTest() {
    final LogConnection logConnection = logConnectionDao.saveAndFlush(new LogConnection("Test",4));
    Assert.assertNotNull(logConnection);
    Assert.assertEquals("Test", logConnection.getClasseName());
    Assert.assertNotEquals(5, logConnection.getOriginalId());
}

}

答案 1 :(得分:1)

在测试类上使用以下类级别注释

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {JPAConfig.class})

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {JPAConfig.class})

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value={"myJPAConfig.xml"})

@RunWith(SpringRunner.class)
@ContextConfiguration(value={"myJPAConfig.xml"})