gpt4 book ai didi

java - Spring 启动(JPA 测试): Unable to find a @SpringBootConfiguration when doing a JpaTest

转载 作者:行者123 更新时间:2023-11-30 06:49:19 25 4
gpt4 key购买 nike

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

我不断收到的错误是:

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?

我的测试类:

@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);
}
}

我的 Spring Boot 应用程序:

@SpringBootApplication
public class UpsysmarocLibraryLogApplication {

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

我的仓库:

public interface LogConnectionDao extends JpaRepository<LogConnection,Long> {

}

最佳答案

我明白了。遵循以下约定

1> 假设您的主要 spring 应用程序如下所示

@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());
}

关于java - Spring 启动(JPA 测试): Unable to find a @SpringBootConfiguration when doing a JpaTest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42998911/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com