如何使用springboot在Junit中模拟来自firebase消息的TopicManagementResponse

o4hqfura  于 2023-11-17  发布在  Spring
关注(0)|答案(1)|浏览(165)

我一直试图模拟我的TopicManagementResponse来测试我的测试类,但即使在使用TopicManagementResponse resposne = Mockito.mock(TopicManagementResponse.class)之后,它仍然说resposne是null。
这是模拟这个类的正确方法吗,或者有什么方法可以做到这一点?
我期望使用TopicManagementResponse对象测试类我的类。但它是null
我的班级:

  1. @PostMapping("/subscribeToTopic")
  2. public int createTopic(@RequestBody Topic topic) throws IOException, FirebaseMessagingException {
  3. String platformID = topic.getPlatformId();
  4. //my internal method to get firebase messaging app
  5. FirebaseMessaging firebaseMessaging = fcmInitializer.getFirebaseMessaging(platformID);
  6. // Get the topic name from the "topic" field in the JSON
  7. String topicName = topic.getTopicName();
  8. // Check if the topic name is not null or empty
  9. if (topicName == null || topicName.isEmpty()) {
  10. return 0;
  11. }
  12. TopicManagementResponse response = firebaseMessaging.subscribeToTopic(topic.getToken(), topicName);
  13. return response.getSuccessCount();
  14. }

字符串
我的测试类:

  1. public void createTopic(){
  2. FirebaseMessaging firebaseMessaging = mock(FirebaseMessaging.class);
  3. TopicManagementResponse response = mock(TopicManagementResponse.class);
  4. Topic topic = new Topic();
  5. topic.setToken("some token");
  6. topic.setTopic("some topic");
  7. when(firebaseMessaging.subscribeToTopic(topic.getToken(), topic.getTopic())).thenReturn(response);
  8. assertEquals(response.getSuccessCount, 1);
  9. }

vu8f3i0k

vu8f3i0k1#

基于这个article关于MockitoJUnit 5你的测试类应该是这样的。

  1. @ExtendWith(MockitoExtension.class)
  2. public class TestClass {
  3. @Mock
  4. private FirebaseMessaging firebaseMessaging;
  5. @Mock
  6. private TopicManagementResponse response;
  7. @Test
  8. public void createTopic(){
  9. when(firebaseMessaging.subscribeToTopic(anyString(), anyString())).thenReturn(response);
  10. when(response.getSuccessCount()).thenReturn(1);
  11. assertEquals(response.getSuccessCount(), 1);
  12. }

字符串
另外,您还必须基于createTopic控制器方法来模拟fcmInitializer.getFirebaseMessaging()

展开查看全部

相关问题