0

NotificationHandler 단위 테스트를 작성하는 데 도움이 필요합니다. 그래서 NotificationHandlerTest (junit4 사용)을 만들었지 만 실제 결과가 무엇인지 예상되는 결과를 결정하는 방법을 알지 못하므로 하나 이상의 간단한 테스트 (일부 메소드)가 제게 많은 도움이됩니다!통합 테스트 통합

import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.integration.annotation.Poller; 
import org.springframework.integration.annotation.ServiceActivator; 
import org.springframework.messaging.Message; 
import org.springframework.stereotype.Component; 

import java.util.List; 
import java.util.stream.Collectors; 

@Component 
class NotificationHandler { 

    private static Logger LOG = LoggerFactory.getLogger(NotificationHandler.class); 

    @Autowired 
    private NotificationRoutingRepository routingRepository; 

    @Autowired 
    private SendNotificationGateway gateway; 

    @Autowired 
    private AccessService accessService; 

    @Autowired 
    private EndpointService endpointService; 

    @ServiceActivator(inputChannel = Channels.ASSET_MODIFIED_CHANNEL, poller = @Poller("assetModifiedPoller"), outputChannel = Channels.NULL_CHANNEL) 
    public Message<?> handle(Message<EventMessage> message) { 
     final EventMessage event = message.getPayload(); 

     LOG.debug("Generate notification messages: {}, {}", event.getOriginType(), event.getType()); 

     routingRepository.findByOriginTypeAndEventType(event.getOriginType(), event.getType()).stream() 
       .filter(routing -> routing.getOriginId() == null || routing.getOriginId() == event.getOriginId()) 
       .map(routing -> getNotificationMessages(event, routing)) 
       .flatMap(List::stream) 
       .forEach(notificationMessage -> { 
        LOG.debug("Sending message {}", notificationMessage); 
        gateway.send(notificationMessage); 
       }); 

     return message; 
    }enter code here 
    enter code here`enter code here` 
    private List<NotificationMessage> getNotificationMessages(EventMessage event, NotificationRouting routing) { 
     switch (routing.getDestinationType()) { 
      case "USERS": 
       LOG.trace("Getting endpoints for users"); 
       return getEndpointsByUsers(routing, event.getOrigin(), event.getOriginType()).stream() 
         .map(endpoint -> new NotificationMessage(event.getOriginType(), event.getOrigin(), endpoint)) 
         .collect(Collectors.toList()); 
      default: 
       LOG.trace("Getting default endpoints"); 
       return getEndpoints(routing, event.getOrigin(), event.getOriginType()).stream() 
         .map(endpoint -> new NotificationMessage(event.getOriginType(), event.getOrigin(), endpoint)) 
         .collect(Collectors.toList()); 
     } 
    } 

    private List<Endpoint> getEndpoints(NotificationRouting routing, Object origin, String originType) { 
     final Asset asset = getAssetForObject(origin, originType); 

     final List<Long> userIds = accessService.list(asset).stream() 
       .map(ResourceAccess::getUser) 
       .map(AbstractEntity::getId) 
       .collect(Collectors.toList()); 

     userIds.add(asset.getCreatorId()); 

     LOG.trace("getEndpoints usersIds {}", userIds); 

     final List<Endpoint> endpoints = endpointService.getEndpoints(userIds, routing.getEndpointType()); 
     LOG.trace("Endpoints {}", endpoints.stream().map(Endpoint::getId).collect(Collectors.toList())); 
     return endpoints; 
    } 

    private List<Endpoint> getEndpointsByUsers(NotificationRouting routing, Object origin, String originType) { 
     final Asset asset = getAssetForObject(origin, originType); 

     final List<Long> userIds = accessService.list(asset).stream() 
       .map(ResourceAccess::getUser) 
       .map(AbstractEntity::getId) 
       .filter(routing.getDestinations()::contains) 
       .collect(Collectors.toList()); 

     routing.setDestinations(userIds); 
     routingRepository.save(routing); 

     LOG.trace("getEndpointsByUsers usersIds {}", userIds); 

     final List<Endpoint> endpoints = endpointService.getEndpoints(userIds, routing.getEndpointType()); 
     LOG.trace("Endpoints {}", endpoints.stream().map(Endpoint::getId).collect(Collectors.toList())); 
     return endpoints; 
    } 

    private Asset getAssetForObject(Object origin, String originType) { 
     switch (originType) { 
      case EventMessage.POINT: 
       return (Point) origin; 
      case EventMessage.FEED: 
       return ((Feed) origin).getPoint(); 
      case EventMessage.ACTUATOR: 
       return ((Actuator)origin).getPoint(); 
      case EventMessage.DEVICE: 
       return (Device) origin; 
      case EventMessage.ALARM: 
       return ((Alarm) origin).getPoint(); 
      default: 
       throw new IllegalArgumentException("Unsupported type: " + originType); 
     } 
    } 

}

+0

당신은 ** 당신이 테스트하고있는 클래스와 그 메소드의 예상되는 동작을 알아야합니다 **. –

+2

[실제 질문이 아닌 이유는 무엇입니까?] (https://meta.stackoverflow.com/q/284236/3788176) –

+1

에 오신 것을 환영합니다. 지금까지 시도한 것을 보여 주시고 구체적인 질문을 해 주시면 구체적인 답변을 드릴 수 있습니다! –

답변

1

난 당신이 테스트 무엇인지 확실하지 않은 경우 간단한 테스트로 시작 말하고 싶지만. null을 인수로 보내면 예외가 없음을 확인하는 테스트가 하나 있습니다.

예.

@Test 
public void shouldNotThrowAnyExceptionIfArgumentIsNull() { 
    // given 
    NotificationHandler handler = new NotificationHandler(); 
    // when 
    handler.handle(null); 
    // then no exception is thrown. 
} 

그 후, 당신은 방법 handle가 무엇을하고 있는지 라인으로 라인을 분석하고 동작을 확인하는 테스트를 작성할 수 있습니다.

매개 변수에서 보낸 내용에 따라 gateway.send(...); 메서드가 실행되었는지 여부를 확인할 수 있습니다.

종속성 조롱 및 동작 확인을 위해 mockito 또는 이와 유사한 도구를 사용하는 것이 좋습니다. this 자습서를 따라 수행 방법을 배울 수 있습니다.