我正在为我的REST API编写集成测试。
下面是这些类。
由于空指针异常,测试失败。当我设置调试断点并检查时,我看到在类CategoryConfiguration
中,this.categoryConfigurationProperties.getValuesFromProperties()
行返回null
。
如何确保在测试中正确初始化CategoryConfigurationProperties
并从application-category.yml
文件加载值?
@RestController
public class MyController {
@Autowired
MyService myService;
public ResponseEntity<MyResponse> createProduct(...) {
myService.createProduct(...);
...
return...;
}
}
@Service
public class MyServiceImpl implements MyService {
@Autowired
MyProductHelper myProductHelper;
public Product createProduct(...) {
Category category = myProductHelper.getCategory(...);
...
}
...
}
@Component
public class MyProductHelper {
@Autowired
@Qualifier("productCategoryMap")
private Map<Product, Category> productCategoryMap;
public Category getCategory(...) {
return productCategoryMap.get(...);
}
}
@Configuration
@EnableConfigurationProperties(CategoryConfigurationProperties.class)
public class CategoryConfiguration {
private final CategoryConfigurationProperties categoryConfigurationProperties;
public CategoryConfiguration(CategoryConfigurationProperties categoryConfigurationProperties) {
this.categoryConfigurationProperties = categoryConfigurationProperties;
}
@Bean(name = "productCategoryMap")
public Map<Product, Category> productCategoryMap() {
this.categoryConfigurationProperties.getValuesFromProperties();
...
return ...;
}
...
}
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "my-config")
@AllArgsConstructor
@Getter
public class CategoryConfigurationProperties {
Map<String,Map<String,List<String>>> valuesFromProperties;
}
@ExtendWith({SpringExtension.class,MockitoExtension.class})
@SpringBootTest(classes = {MyApplication.class},webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ContextConfiguration(classes = CategoryConfiguration.class)
@ActiveProfiles(profiles = "test")
@AutoConfigureMockMvc
@TestPropertySource(properties = {"spring.config.location=classpath:application-category.yml,classpath:application.properties"})
class MyControllerIntegrationTest {
@Autowired
private MockMvc mockMvc;
@Autowired
WebApplicationContext webApplicationContext;
@MockBean
CategoryConfiguration categoryConfiguration;
@BeforeEach
public void setup() {
...
}
@Test
void testCreateProduct() {
MvcResult result = mockMvc.perform(...);
// assert
}
}
1条答案
按热度按时间iibxawm41#
我刚刚解决了我的项目中的相同问题。
How to test Externalized Configuration reading from yaml
看一看,特别是在使用的注解,你需要找到正确的组合。