Spring Boot 使用Junit访问properties.yml文件数据时遇到的困难

iqxoj9l9  于 2023-04-06  发布在  Spring
关注(0)|答案(1)|浏览(128)

这是我的测试类“AsyncPublisherServiceImplTest”,我的mock类是“AsyncPublisherServiceImpl”,当mock时,我得到了此属性的null数据**"@Value(“${aws.s3.bucketName}”)private String bucketName;“**,你能帮我,我怎么能得到这个属性的值.
在传递“link = uploadFileToS 3(bucketName,Regions.US_WEST_2,uuid +“.zip”,file)”时,此处的bucketName为null

@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
public class AsyncPublisherServiceImplTest {

    @InjectMocks
    private AsyncPublisherServiceImpl asyncPublisherServiceImpl;

    @Mock
    private AsyncPublisherDao dao;
    @Mock
    private AsyncUtil asyncUtil;
    @Mock
    private ClientListenerService techpulseservice;

    @Test
    void publish() {
        String link = null;
        PublisherRequest PublisherRequest = RequestUtils.getPublisherRequest();

        lenient().when(dao.isValidCount(ConstantsTest.UUID)).thenReturn(true);
        File file = new File(AsyncUtil.sanitizePathandfilename(ConstantsTest.UUID + ".zip"));
        assertNotNull(asyncPublisherServiceImpl.publish(PublisherRequest.getUuid(), ConstantsTest.UnitOfWorkId));
    }

}

模拟类是“AsyncPublisherServiceImpl”

@Service
@Transactional
public class AsyncPublisherServiceImpl implements AsyncPublisherService {
    Logger logger = LoggerFactory.getLogger(this.getClass().getName());
    @Autowired
    private AsyncPublisherDao dao;
    @Autowired
    private AsyncUtil asyncUtil;
    @Autowired
    private ClientListenerService techpulseservice;

    @Value("${aws.s3.bucketName}")
    private String bucketName;

    @Override
    public boolean publish(final String uuid, final String userName) {
        boolean validCount = dao.isValidCount(uuid);

        if (validCount) {
            try {
                dao.updateMainStatus(uuid, Status.Processed.name());
                logger.info("current state-->" + Status.Processed.name());
            } catch (Exception e) {
                e.printStackTrace();
                throw new StatusUpdateException("Exception while updating status in DB");
            }
            final List<JsonNode> response = dao.fetchResponse(uuid, Status.Completed.name());

            if (response != null) {
                // create a zip file for all json response
                ObjectMapper om = new ObjectMapper();

                try {
                    logger.info("response from db --->" + om.writeValueAsString(response));
                } catch (JsonProcessingException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                    throw new InternalErrorException("Exception while processing Json");
                }
                byte[] bytestream = asyncUtil.generateZip(uuid, response);
                logger.info("bytestream--->" + bytestream.toString());
                logger.info("Zip file process started --->" + uuid);
                // upload file to s3 bucket
                File file = new File(AsyncUtil.sanitizePathandfilename(uuid + ".zip"));
                String link = null;
                try {
                    FileUtils.writeByteArrayToFile(file, bytestream);
                    logger.info("Zip file generated--->" + uuid);
                    link = uploadFileToS3(bucketName, Regions.US_WEST_2, uuid + ".zip", file);
                } catch (IOException e) {
                    logger.error("exception in generating zip file" + e.getMessage());
                    throw new CommonException("Exception while uploading file");
                } catch (Exception e) {
                    logger.error("exception in generating zip file" + e.getMessage());
                    throw new CommonException("Exception while uploading file");
                }

                dao.updateLink(uuid, link);
                // publish zip file to techpulse listner
                logger.info("file uploaded to S3 bucket-->" + uuid);
                try {

                    techpulseservice.callRemoteListenerService(uuid, userName, true, file);
                } catch (FileNotFoundException e) {
                    logger.error("Exception in calling tech pulse" + e.getMessage());
                    throw new CommonException("Exception while receiving file");
                }
            }
            dao.updateStatus(uuid, Status.Completed.name());
            logger.info("current child state-->" + Status.Completed.name());
        }
        return validCount;
    }

YML aws:s3:region:“us-west-2”bucketName:“hpmap-pro-development-os-asyncmulti”错误日志

com.hp.it.psoit.asyncdelegator.exception.CommonException: Exception while uploading file
    at com.hp.it.psoit.asyncdelegator.service.impl.AsyncPublisherServiceImpl.publish(AsyncPublisherServiceImpl.java:85)
    at com.hp.it.psoit.asyncdelegator.service.impl.AsyncPublisherServiceImplTest.publish(AsyncPublisherServiceImplTest.java:66)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:727)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:156)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:147)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:86)
    at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(InterceptingExecutableInvoker.java:103)
    at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.lambda$invoke$0(InterceptingExecutableInvoker.java:93)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.invoke(InterceptingExecutableInvoker.java:92)
    at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.invoke(InterceptingExecutableInvoker.java:86)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:217)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:213)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:138)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:68)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
doinxwow

doinxwow1#

您可以尝试在您的测试类AsyncPublisherServiceImplTest上添加@SpringBootTest来强制spring加载ApplicationContext

@ExtendWith(MockitoExtension.class)
@SpringBootTest 
@MockitoSettings(strictness = Strictness.LENIENT)
public class AsyncPublisherServiceImplTest {

    @InjectMocks
    private AsyncPublisherServiceImpl asyncPublisherServiceImpl;

    @Mock
    private AsyncPublisherDao dao;
    @Mock
    private AsyncUtil asyncUtil;
    @Mock
    private ClientListenerService techpulseservice;

    @Test
    void publish() {
        String link = null;
        PublisherRequest PublisherRequest = RequestUtils.getPublisherRequest();

        lenient().when(dao.isValidCount(ConstantsTest.UUID)).thenReturn(true);
        File file = new File(AsyncUtil.sanitizePathandfilename(ConstantsTest.UUID + ".zip"));
        assertNotNull(asyncPublisherServiceImpl.publish(PublisherRequest.getUuid(), ConstantsTest.UnitOfWorkId));
    }

}

相关问题