如何对Spring存储库进行单元测试?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (106)

我创建了一个springboot项目,分为三个maven模块,域层,核心层和Web层。我尝试对我的存储库ProductRepository进行单元测试:

@RunWith(SpringRunner.class) // provide bridge between SpringBoot test features and JUnit, for usage of springboot tsting features
@DataJpaTest
class ProductRepositoryTest {
	@Autowired
	private TestEntityManager em;
	@Autowired
	private ProductRepository repository;
	

	@Test
	void shouldReturnProduct() {
		// given
		Product p = Product.builder().id(1).designation("Test").reference("TEST").unitPrice(150).build();
		this.em.persistAndFlush(p);
		// when
		Product found = repository.findByReference(p.getReference());
		// then
		assertThat(found.getReference()).isEqualTo(p.getReference());
	}

}

但是存储库总是被设置为null。我在eclipse中运行这个测试作为JUnit Test,我得到了一个nullpointerexception。

这是我的pom.xml文件:

<dependencies>
		<!--<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> 
			</dependency> -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.junit.jupiter</groupId>
			<artifactId>junit-jupiter-engine</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-tomcat</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency> 
	</dependencies>
提问于
用户回答回答于

将这些注释添加到测试类中。

@SpringBootTest
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
    DbUnitTestExecutionListener.class,
    TransactionalTestExecutionListener.class })
public class YourTestClass {....
用户回答回答于

我认为你自己的项目中可能存在一些冲突的配置或依赖项。

扫码关注云+社区

领取腾讯云代金券