【发布时间】:2018-02-03 23:24:57
【问题描述】:
我是 Web 服务和 Spring Boot 的新手。我已经编写了一个服务,我现在正在为其编写一个测试用例。
我的应用程序收到 Soap 请求,解析正文并将内容保存到数据库中。 我的测试用例测试了这项服务。
当我运行应用程序并从 Postman 发送请求时,它运行正常。但是当我从测试用例调用我的服务方法时,我得到了 JaxBcontext 的空指针。
我已经在我的服务中的 AppConfig.java 中声明了 Jaxbcontext(它使用 @Configuration 注释,我的 jaxb 是带有 @Bean 注释的 bean),我有 @autowire 来使用 jaxbcontext。
为了清楚起见,我粘贴了代码 sn-ps。请告诉我我在这里做错了什么。
我的测试用例
public class ReferralExchangeEndpointTest {
ReferralExchangeEndpoint referralExchangeEndpoint = new ReferralExchangeEndpoint();
JAXBContext jbcTest;
Marshaller marshaller;
Unmarshaller unmarshaller;
public ReferralExchangeEndpointTest() throws JAXBException {
}
@Before
public void setUp() throws Exception {
jbcTest = JAXBContext.newInstance(
"our app schema"); // this is working fine, I have replaced schema with this text for posting it in stack.
ObjectFactory factory = new ObjectFactory();
marshaller = jbcTest.createMarshaller();
unmarshaller = jbcTest.createUnmarshaller();
}
@Test
public void send() throws Exception {
File payload = new File("payload.xml");
Object x = unmarshaller.unmarshal(payload);
JAXBElement jbe = (JAXBElement) x;
System.out.println(jbe.getName());
Object test = jbe.getValue();
SendRequestMessage sendRequestMessage = (SendRequestMessage) jbe.getValue();
// Method in test.
referralExchangeEndpoint.send(sendRequestMessage);
}
}
我的服务类
@Endpoint
public class ReferralExchangeEndpoint {
public static final Logger logger = LoggerFactory.getLogger(ReferralExchangeEndpoint.class);
@Autowired
private JAXBContext jaxbContext;
@Autowired
.
.
.
private Form parseBody(String payLoadBody) {
try {
Unmarshaller um = jaxbContext.createUnmarshaller();
return (Form) um.unmarshal(new StringReader(payLoadBody));
} catch (Exception e) {
throw new RuntimeException("Failed to extract the form from the payload body", e);
}
}
我的 appconfig 文件
@Configuration
public class AppConfig {
@Bean
public JAXBContext jaxbContext() throws JAXBException {
return
JAXBContext.newInstance("packagename");
}
@Bean public MessagingService messagingService() {
return new MessagingService();
}
}
谢谢。 卡维莎。
【问题讨论】:
-
您的设置不是线程安全的。我建议使用 Spring oxm docs.spring.io/spring-ws/site/reference/html/oxm.html 重构和设置它。您可能没有遇到任何并发问题,因为我猜您正在使用 1 个请求进行本地测试。
-
谢谢 Darren,但是通过使用它,我是否可以解决实例化 AppConfig 属性以供我的应用程序使用的问题?还是我必须做其他事情才能让它发挥作用?
-
感谢 Darren,我将阅读有关 OXM 的更多信息并将其用于我的端点实现。
标签: unit-testing spring-boot configuration