gpt4 book ai didi

java - Spring Boot 存储库在测试期间不工作

转载 作者:行者123 更新时间:2023-12-02 10:09:41 25 4
gpt4 key购买 nike

我搜索了 Google 和 SO 答案,并尝试了许多变体,但没有成功。在过去的几天里,我正在尝试为我的 Spring Boot 端点启用集成测试。详细信息如下:

错误是在 EnclosureController 类中发现 NullPointerException(我在注释中用 NULL 标记了该对象)

如果存在一种比 MockMvc 更有效的方法来执行集成测试,我非常愿意接受建议。

TestClass(在 root.package.test 中)

@RunWith(SpringRunner.class)
@WebMvcTest(EnclosureController.class)
public class EnclosureControllerTest {

@Autowired
private MockMvc mvc;

@MockBean
private EnclosureRepository enclosureRepository;

//static final strings for Enclosure initialization

@Test
public void createEnclosureAPI() throws Exception
{
mvc.perform( MockMvcRequestBuilders
.post("/enclosure")
.header("Authorization", "TEST")
.content(asJsonString(new Enclosure(ENCLOSURE_TITLE, ENCLOSURE_LOCATION, DIMENSIONAL_UNITS, ENCLOSURE_LENGTH, ENCLOSURE_WIDTH, ENCLOSURE_HEIGHT)))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isCreated())
.andDo(print())
.andExpect(MockMvcResultMatchers.jsonPath("$.enclosureId").exists());
}
}

EnclosureController(我删除了身份验证检查,因为错误与存储库有关)

@RestController
public class EnclosureController {

final
private EnclosureRepository repository;

@Autowired
public EnclosureController(EnclosureRepository repository) {
this.repository = repository;
}

@RequestMapping(value = {"/enclosure"},
method = RequestMethod.POST,
consumes = "application/json",
produces = APPLICATION_JSON_VALUE)
@ResponseBody
@Async("asyncExecutor")
public CompletableFuture<Enclosure> createEnclosure(
@Valid @RequestBody Enclosure request,
@RequestHeader(value = "Authorization") String auth,
HttpServletResponse response
) {

//NULL on repository (Optional is never returned. NullPointerExcep thrown on repository.save)
int enclosureId = Optional.of(repository.save(request)).orElse(new Enclosure(0)).getEnclosureId();

if (enclosureId > 0)
response.setStatus(HttpServletResponse.SC_CREATED);

return CompletableFuture.completedFuture(repository.findByEnclosureId(enclosureId));

}

}
@RequestMapping(value = {"/enclosure/{id}"},
method = RequestMethod.GET)
@ResponseBody
@Async("asyncExecutor")
public CompletableFuture<Enclosure> getSingleEnclosure(
@PathVariable("id") int id,
@RequestHeader(value = "Authorization") String auth,
HttpServletResponse response
) {

return CompletableFuture.completedFuture(repository.findByEnclosureId(id));

}

存储库

@Repository
public interface EnclosureRepository extends CrudRepository<Enclosure, Integer> {
Enclosure findByEnclosureId(Integer enclosureId);
List<Enclosure> findAll();
}

RepositoryImpl(用于 bean decleration。注意删除了本文中不需要的方法)

public class EnclosureRepositoryImpl implements EnclosureRepository {

private static ConcurrentHashMap<Integer, Optional<Enclosure>> repo = new ConcurrentHashMap<>();
private static AtomicInteger maxId = new AtomicInteger();

@Override
public Enclosure findByEnclosureId(Integer enclosureId) {
return repo.get(enclosureId).orElse(new Enclosure());
}

@Override
public Enclosure save(Enclosure entity) {

repo.put(maxId.incrementAndGet(), Optional.of(entity));

return repo.get(maxId).orElse(new Enclosure());
}

@Override
public Optional<Enclosure> findById(Integer integer) {
return repo.get(integer);
}

@Override
public boolean existsById(Integer integer) {
return repo.containsKey(integer);
}
}

申请

@SpringBootApplication
public class Application {

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

配置

@Configuration
@EnableJpaRepositories(basePackages = {
"root.package.model.repository"
})
@EnableTransactionManagement
@EnableAsync
public class BeanConfig {

@Override
@Bean(name = "asyncExecutor")
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(3);
executor.setMaxPoolSize(100);
executor.setQueueCapacity(100);
executor.setThreadNamePrefix("AGMSpringAsyncThread-");
executor.initialize();

return executor;
}

@Bean
JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}

@Bean
LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource,
Environment env) {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource);
entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
entityManagerFactoryBean.setPackagesToScan("io.colby.model.repository");

Properties jpaProperties = new Properties();

//Configures the used database dialect. This allows Hibernate to create SQL
//that is optimized for the used database.
jpaProperties.put("hibernate.dialect", env.getRequiredProperty("hibernate.dialect"));

//Specifies the action that is invoked to the database when the Hibernate
//SessionFactory is created or closed.
jpaProperties.put("hibernate.hbm2ddl.auto",
env.getRequiredProperty("hibernate.hbm2ddl.auto")
);

//Configures the naming strategy that is used when Hibernate creates
//new database objects and schema elements
jpaProperties.put("hibernate.ejb.naming_strategy",
env.getRequiredProperty("hibernate.ejb.naming_strategy")
);

//If the value of this property is true, Hibernate writes all SQL
//statements to the console.
jpaProperties.put("hibernate.show_sql",
env.getRequiredProperty("hibernate.show_sql")
);

//If the value of this property is true, Hibernate will format the SQL
//that is written to the console.
jpaProperties.put("hibernate.format_sql",
env.getRequiredProperty("hibernate.format_sql")
);

entityManagerFactoryBean.setJpaProperties(jpaProperties);

return entityManagerFactoryBean;
}

@Bean(destroyMethod = "close")
DataSource dataSource(Environment env) {
HikariConfig dataSourceConfig = new HikariConfig();
dataSourceConfig.setDriverClassName(env.getRequiredProperty("db.driver"));
dataSourceConfig.setJdbcUrl(env.getRequiredProperty("db.url"));
dataSourceConfig.setUsername(env.getRequiredProperty("db.username"));
dataSourceConfig.setPassword(env.getRequiredProperty("db.password"));

return new HikariDataSource(dataSourceConfig);
}

@Bean
public EnclosureRepository enclosureRepository(){
return new EnclosureRepositoryImpl();
}
}

外壳

@Component
@Entity
@Table(name="enclosure")
public class Enclosure {


@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "enclosure_id", nullable = false, updatable = false)
@JsonProperty("enclosure-id")
private Integer enclosureId;

@Column(name = "title")
@Size(max = 255)
@NotBlank
private String title;

@Column(name = "location")
@Size(max = 255)
private String location;

@Column(length = 25, name = "dimension_units")
@Size(max = 25)
@JsonProperty("dimension-units")
private String dimensionUnits;

@CreationTimestamp
@Column(nullable = false, name = "insert_timestamp")
@JsonProperty("created-date-time")
private LocalDateTime insertTimestamp;

@UpdateTimestamp
@Column(name = "update_timestamp")
@JsonProperty("last-updated-date-time")
private LocalDateTime updateTimestamp;


@Column(length = 5, precision = 2)
private double length;
@Column(length = 5, precision = 2)
private double width;
@Column(length = 5, precision = 2)
private double height;

public Enclosure(String title,
String location,
String dimensionUnits,
double length, double width, double height) {
this.title = title;
this.location = location;
this.dimensionUnits = dimensionUnits;
this.length = length;
this.width = width;
this.height = height;
}

public Enclosure(int enclosureId){
this.enclosureId = enclosureId;
}

public Enclosure(){

}
//Getters and setters...

目录树

.
└── main
├── java
│   └── root
│   └── package
│   ├── Application.java
│   ├── configuration
│   │   ├── BeanConfig.java
│   ├── model
│   │   ├── entity
│   │   │   ├── Enclosure.java
│   │   └── repository
│   │   ├── EnclosureRepository.java
│   │   ├── EnclosureRepositoryImpl.java
│   ├── routes
│   │   ├── enclosure
│   │   │   └── controller
│   │   │   └── EnclosureController.java
│   └── test
│   └── routes
│   └── enclosure
│   └── EnclosureControllerTest.java
├── resources
│   ├── application.properties
└── test
└── java

应用程序属性

 #Database Configuration
db.driver=org.h2.Driver
db.url=jdbc:h2:mem:datajpa
db.username=sa
db.password=

spring.jackson.default-property-inclusion=non_null

# Details for our datasource
spring.datasource.url = jdbc:postgresql://host/db
spring.datasource.username = user
spring.datasource.password = pass

# Hibernate properties
spring.jpa.database-platform = org.hibernate.dialect.PostgreSQL94Dialect
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = create-drop
spring.jpa.hibernate.naming.implicit-strategy = org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl
spring.jpa.properties.hibernate.format_sql=true

注意,我在 test.java 中有测试类,但是我想让测试在 root.package 子目录中工作,然后使用 @ComponentScan 指向要扫描的包树。

我正在查看以下教程来尝试进行测试:

http://www.springboottutorial.com/integration-testing-for-spring-boot-rest-services
https://www.baeldung.com/spring-boot-testing

最佳答案

当通过注解创建模拟时,即@Mock,您需要初始化它们。最好的方法是调用:

MockitoAnnotations.initMocks(this);

在用@Before注释的方法内,以便在调用测试之前创建模拟。

关于java - Spring Boot 存储库在测试期间不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55089558/

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