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

o4hqfura  于 7个月前  发布在  Spring
关注(0)|答案(1)|浏览(71)

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

@PostMapping("/subscribeToTopic")
    public int createTopic(@RequestBody Topic topic) throws IOException, FirebaseMessagingException {
 
        String platformID = topic.getPlatformId();

        //my internal method to get firebase messaging app
        FirebaseMessaging firebaseMessaging = fcmInitializer.getFirebaseMessaging(platformID);
 
        // Get the topic name from the "topic" field in the JSON
        String topicName = topic.getTopicName();
 
        // Check if the topic name is not null or empty
        if (topicName == null || topicName.isEmpty()) {
            return 0;
        }
        TopicManagementResponse response = firebaseMessaging.subscribeToTopic(topic.getToken(), topicName);
        return response.getSuccessCount();
 
    }

字符串
我的测试类:

public void createTopic(){
FirebaseMessaging firebaseMessaging = mock(FirebaseMessaging.class);
    TopicManagementResponse response = mock(TopicManagementResponse.class);

    Topic topic = new Topic();
    topic.setToken("some token");
    topic.setTopic("some topic");
    

    when(firebaseMessaging.subscribeToTopic(topic.getToken(), topic.getTopic())).thenReturn(response);

    assertEquals(response.getSuccessCount, 1);

}

vu8f3i0k

vu8f3i0k1#

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

@ExtendWith(MockitoExtension.class)
    public class TestClass {
    
      @Mock
      private FirebaseMessaging firebaseMessaging;
    
      @Mock
      private TopicManagementResponse response;
    
      @Test
      public void createTopic(){
    
        when(firebaseMessaging.subscribeToTopic(anyString(), anyString())).thenReturn(response);
        when(response.getSuccessCount()).thenReturn(1);
    
        assertEquals(response.getSuccessCount(), 1);
        

  }

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

相关问题