Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring 无法在JUnit 5中使用@value获取属性值_Spring_Spring Boot_Junit_Junit4_Junit5 - Fatal编程技术网

Spring 无法在JUnit 5中使用@value获取属性值

Spring 无法在JUnit 5中使用@value获取属性值,spring,spring-boot,junit,junit4,junit5,Spring,Spring Boot,Junit,Junit4,Junit5,在我的服务实现类中,我试图使用@value从application.properties获取值。它工作得很好。但在为它编写测试用例时,我得到了空值 内部服务impl类 @Value("${transaction.service.process.layer.url}") private String processLayerUrl; public ResponseEntity<Object> getTransactionDataListByAccount(Tran

在我的服务实现类中,我试图使用@value从application.properties获取值。它工作得很好。但在为它编写测试用例时,我得到了空值

内部服务impl类

@Value("${transaction.service.process.layer.url}")
private String processLayerUrl;

public ResponseEntity<Object> getTransactionDataListByAccount(Transaction transaction) {
    ResponseEntity<Object> transactionHistoryResponse = restTemplate.postForEntity(processLayerUrl, transaction, Object.class);        
    return new ResponseEntity<>(transactionHistoryResponse.getBody(), HttpStatus.OK);
}

由于此restTemplate正在抛出NullPointerException而不是返回mock obj。

之所以发生这种情况,是因为您使用的是Mockito注释,而不是Spring Boot提供的注释

transactionService
应使用
@Autowired
mockrestemplate
注释
@MockBean

@MockBean
在Spring应用程序上下文中添加或替换原始bean,并将其作为依赖项注入到该上下文中的任何bean中

如果您正在编写的测试是集成测试,则不应手动实例化transactionService


您还应该重新考虑您在这里测试的内容——WebMvc测试的目的是测试控制器,而不是服务。如果要测试服务,请考虑在没有Spring的情况下编写简单的单元测试。如果您想要真正的集成测试,请考虑使用<代码> @ Spring BooTest< <代码> .< /P> < P>这是因为您使用的是MoCKITO注释,而不是Spring Bug提供的。
transactionService
应使用
@Autowired
mockrestemplate
注释
@MockBean

@MockBean
在Spring应用程序上下文中添加或替换原始bean,并将其作为依赖项注入到该上下文中的任何bean中

如果您正在编写的测试是集成测试,则不应手动实例化transactionService


您还应该重新考虑您在这里测试的内容——WebMvc测试的目的是测试控制器,而不是服务。如果要测试服务,请考虑在没有Spring的情况下编写简单的单元测试。如果您想要真正的集成测试,请考虑使用<代码> @ SpRunBooTest。我按照你的建议做了必要的修改。我正在获取属性值,但restTemplate仍返回null,而不是我定义的responseEntity对象。是否确实模拟了正确的调用?也许您可以在最后使用mockitoverify来检查这个方法是否真的被调用了。服务类中的实际方法正在被调用。但是restTemplate返回的是null,而不是我传入的responseEntity对象。Return()添加了服务impl类的代码。谢谢。我按照你的建议做了必要的修改。我正在获取属性值,但restTemplate仍返回null,而不是我定义的responseEntity对象。是否确实模拟了正确的调用?也许您可以在最后使用mockitoverify来检查这个方法是否真的被调用了。服务类中的实际方法正在被调用。但是restTemplate返回的是null,而不是我传入的responseEntity对象。然后return()添加了服务impl类的代码。
@RunWith(SpringRunner.class)
@WebMvcTest(value = TransactionServiceImpl.class)
@ActiveProfiles(profiles = "test")
@ContextConfiguration
//@ContextConfiguration(classes = TransactionServiceExperienceApplication.class)
//@SpringBootConfiguration(classes = { TransactionServiceExperienceApplicationTests.class })
//@TestPropertySource(locations="classpath:application-test.properties")
//@SpringBootTest(properties = { "transaction.service.process.layer.url =http://localhost:8087/v1/transaction-process-service" })
//@TestPropertySource(properties = { "transaction.service.process.layer.url = http://localhost:8087/v1/transaction-process-service" })
public class TransactionServiceImplTest {

    @Mock 
    private RestTemplate mockRestTemplate;
    
    @InjectMocks
    private TransactionServiceImpl transactionService;
    
    @Before
    public void setUp() {
        //transactionService = new TransactionServiceImpl("test");
        //ReflectionTestUtils.setField(transactionService, "processLayerUrl", "foo");
    }
    
    @Test 
    public void getTransactionDataListByAccountTest() throws Exception{
        
        Transaction transaction = new Transaction();
        transaction.setPosAccountNumber("40010020070401");
        
        HttpHeaders header = new HttpHeaders();
        header.setContentType(MediaType.APPLICATION_JSON);
        
        ArrayList<Object> mockResponseObj = new ArrayList<Object>();
        //Added data inside this object

        ResponseEntity<Object> responseEntity = new ResponseEntity<>(mockResponseObj, HttpStatus.OK);
        
        when(mockRestTemplate.postForEntity(
                ArgumentMatchers.anyString(), 
                ArgumentMatchers.eq(Transaction.class), 
                ArgumentMatchers.eq(Object.class))).thenReturn(responseEntity);
        
        ResponseEntity<Object> actualResponse = transactionService.getTransactionDataListByAccount(transaction);
        
        System.out.println("--- Response ---");
        System.out.println(actualResponse);
    }
    
    /*
     * @Configuration
     * 
     * @ComponentScan("transaction.service.experience.service") static class
     * someConfig {
     * 
     * // because @PropertySource doesnt work in annotation only land
     * 
     * @Bean PropertySourcesPlaceholderConfigurer propConfig() {
     * PropertySourcesPlaceholderConfigurer ppc = new
     * PropertySourcesPlaceholderConfigurer(); ppc.setLocation(new
     * ClassPathResource("application.properties")); return ppc; } }
     */
}
testImplementation('org.springframework.boot:spring-boot-starter-test') {
    exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
implementation 'junit:junit:4.12'