Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do Junit Test with Google Cloud Pub/Sub

I'm using push pub/sub of Google Cloud Pub/Sub in my system,and I want to build my CI test code but I don't know how to do it.For example,some codes are like this:

final Pubsub pubsub = PubsubUtils.getClient();
final PubsubMessage pubsubMessage = new PubsubMessage();

pubsubMessage.encodeData(message.getBytes(StandardCharsets.UTF_8));
Map<String, String> attrs = new HashMap<String, String>();
attrs.put("key", "value");
pubsubMessage.setAttributes(attrs);

final List<PubsubMessage> messages = ImmutableList.of(pubsubMessage);
final PublishRequest publishRequest = new PublishRequest().setMessages(messages);
        final PublishResponse publishResponse = pubsub.projects().topics().publish(topic, publishRequest).execute();
        final List<String> messageIds = publishResponse.getMessageIds();

and this:

final ServletInputStream reader = request.getInputStream();
        try {
            // Parse the JSON message to the POJO model class.
            final JsonParser parser = JacksonFactory.getDefaultInstance().createJsonParser(reader);

            parser.skipToKey("message");

            final PubsubMessage message = parser.parseAndClose(PubsubMessage.class);

            Map<String, String> attrs = message.getAttributes();
            String value = attrs.get("key");

            // Base64-decode the data and work with it.
            final String data = new String(message.decodeData(), StandardCharsets.UTF_8);
            if (data != null || StringUtils.isNotEmpty(data)) {
                Logger.getLogger("logger").info(data);
            }
            // Work with your message
            // Respond with a 20X to acknowledge receipt of the message.
            response.setStatus(HttpServletResponse.SC_OK);
        } finally {
            reader.close();
        }

How to write a normally Junit test case for the two parts of code? and also,I'm using PowerMockito to mock the objects.

Hope someone can help me.

like image 565
xialin Avatar asked Jul 31 '15 06:07

xialin


People also ask

How does Pub/Sub work in GCP?

Google Cloud Pub/Sub provides messaging between applications. Cloud Pub/Sub is designed to provide reliable, many-to-many, asynchronous messaging between applications. Publisher applications can send messages to a "topic" and other applications can subscribe to that topic to receive the messages.

Does Pub/Sub use HTTP?

Pub/Sub offers push-based delivery of messages as HTTP POST requests to webhooks. You can implement workflow automation using Cloud Functions or other serverless products.


1 Answers

For unit testing the first example, you can mock the Pub/Sub client object with desired return values for API calls like:

import com.google.api.services.pubsub.Pubsub;
import com.google.api.services.pubsub.Pubsub.Projects;
import com.google.api.services.pubsub.Pubsub.Projects.Topics;
import com.google.api.services.pubsub.Pubsub.Projects.Topics.Create;
import com.google.api.services.pubsub.Pubsub.Projects.Topics.Publish;
// ...
@Mock private Pubsub mockPubsub;
@Mock private Projects mockProjects;
@Mock private Topics mockTopics;
@Mock private Create mockCreate;
@Mock private Publish mockPublish;
// ...
String topicName = "projects/myproject/topics/mytopic";
String messageId = "messageId";
List<String> messageIds = ImmutableList.of(messageId);
PublishResponse publishResponse = new PublishResponse()
        .setMessageIds(messageIds);

when(mockPubsub.projects()).thenReturn(mockProjects);
when(mockProjects.topics()).thenReturn(mockTopics);
when(mockTopics.publish(eq(topicName), isA(PublishRequest.class)))
        .thenReturn(mockPublish);
when(mockPublish.execute()).thenReturn(publishResponse);

For the second example, you can mock the HttpServletRequest and HttpServletResponse then call the servlet with these mock objects.

like image 147
Takashi Matsuo Avatar answered Nov 10 '22 13:11

Takashi Matsuo