Ejemplo n.º 1
0
  /**
   * Analyzes the data file identified by the given resource name.
   *
   * @param aResourceName the name of the resource (= data file) to analyse, cannot be <code>null
   *     </code>.
   * @return the analysis results, never <code>null</code>.
   * @throws Exception in case of exceptions.
   */
  private I2CDataSet analyseDataFile(
      final String aResourceName, final int aSclIndex, final int aSdaIndex) throws Exception {
    URL resource = ResourceUtils.getResource(getClass(), aResourceName);
    AcquisitionResult container = DataTestUtils.getCapturedData(resource);
    ToolContext toolContext = DataTestUtils.createToolContext(container);

    ToolProgressListener progressListener = Mockito.mock(ToolProgressListener.class);
    AnnotationListener annotationListener = Mockito.mock(AnnotationListener.class);

    I2CAnalyserTask worker = new I2CAnalyserTask(toolContext, progressListener, annotationListener);
    worker.setLineAIndex(aSclIndex);
    worker.setLineBIndex(aSdaIndex);
    worker.setDetectSDA_SCL(false);
    worker.setReportACK(false);
    worker.setReportNACK(false);
    worker.setReportStart(false);
    worker.setReportStop(false);

    // Simulate we're running in a separate thread by directly calling the main
    // working routine...
    I2CDataSet result = worker.call();
    assertNotNull(result);

    return result;
  }
  @Test
  public void testRemoveArticle() throws Exception {

    MessageResponseServiceImpl mrs = new MessageResponseServiceImpl();

    // Successful case
    mrs.setMessageResponse(new MessageResponse());
    articleService.setMessageResponseService(mrs);

    Article articleSuccess = new Article();
    articleSuccess.setTitle("test success");
    articleSuccess.setDeleted(true);

    Mockito.when(articleDao.removeArticle(articleSuccess)).thenReturn(articleSuccess);

    MessageResponse messageSuccess = articleService.removeArticle(articleSuccess);

    // Fail case
    mrs.setMessageResponse(new MessageResponse());
    articleService.setMessageResponseService(mrs);

    Article articleFail = new Article();
    articleFail.setTitle("test fail");
    articleFail.setDeleted(false);

    Mockito.when(articleDao.removeArticle(articleFail)).thenReturn(articleFail);

    MessageResponse messageFail = articleService.removeArticle(articleFail);

    Assert.assertTrue(messageSuccess.getCode() == 1 && messageFail.getCode() == 0);
  }
  @Test
  public void testValidSubscription() {
    // add configuration
    // Mock the task scheduler and capture the runnable
    ArgumentCaptor<Runnable> runnableArg = ArgumentCaptor.forClass(Runnable.class);
    when(taskScheduler.scheduleWithFixedDelay(runnableArg.capture(), anyLong()))
        .thenReturn(Mockito.mock(ScheduledFuture.class));

    // Mock the response to the subsribeContext
    ArgumentCaptor<SuccessCallback> successArg = ArgumentCaptor.forClass(SuccessCallback.class);
    ListenableFuture<SubscribeContextResponse> responseFuture =
        Mockito.mock(ListenableFuture.class);
    doNothing().when(responseFuture).addCallback(successArg.capture(), any());

    Configuration configuration = getBasicConf();
    subscriptionManager.setConfiguration(configuration);

    // Capture the arg of subscription and return the mocked future
    ArgumentCaptor<String> urlProviderArg = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<SubscribeContext> subscribeContextArg =
        ArgumentCaptor.forClass(SubscribeContext.class);
    when(ngsiClient.subscribeContext(
            urlProviderArg.capture(), eq(null), subscribeContextArg.capture()))
        .thenReturn(responseFuture);

    // Execute scheduled runnable
    runnableArg.getValue().run();

    // Return the SubscribeContextResponse
    callSuccessCallback(successArg);

    // check ngsiClient.unsubscribe() is never called
    verify(ngsiClient, never()).unsubscribeContext(any(), any(), any());
    subscriptionManager.validateSubscriptionId("12345678", "http://iotAgent");
  }
  /**
   * Check uploading files and create attachments
   *
   * @throws Exception
   */
  @Test
  public void testCreateAttachment() throws Exception {

    List<MultipartFile> files = new ArrayList<>();
    files.add(multipartFile);

    Mockito.when(attachmentFactory.newAttachment()).thenReturn(null);

    attachmentService.setAttachment(new Attachment());
    attachmentService.setMessageResponse(new MessageResponse());

    MessageResponse messageResponse = attachmentService.createAttachment(files);

    Mockito.verify(attachmentDao, Mockito.times(1)).createAttachments(argumentCaptor.capture());

    Attachment attachment = argumentCaptor.getValue().get(0);

    boolean isExistPreview = Files.exists(Paths.get(storagePath + attachment.getPreviewPath()));
    boolean isExistImage = Files.exists(Paths.get(storagePath + attachment.getFilePathInStorage()));

    Files.delete(Paths.get(storagePath + attachment.getPreviewPath()));
    Files.delete(Paths.get(storagePath + attachment.getFilePathInStorage()));

    Assert.assertTrue(
        attachment.getMimeType().equals("image/png")
            && messageResponse.getCode() == 0
            && isExistPreview
            && isExistImage);
  }
  @Test
  public void testRemoveAttachment() throws Exception {

    // CREATING ATTACHMENT FOR REMOVE
    List<MultipartFile> files = new ArrayList<>();
    files.add(multipartFile);

    Mockito.when(attachmentFactory.newAttachment()).thenReturn(null);

    attachmentService.setAttachment(new Attachment());
    attachmentService.setMessageResponse(new MessageResponse());

    MessageResponse messageResponse1 = attachmentService.createAttachment(files);

    Mockito.verify(attachmentDao, Mockito.times(1)).createAttachments(argumentCaptor.capture());

    Attachment attachment = argumentCaptor.getValue().get(0);

    // REMOVE ATTACHMENT
    Mockito.when(attachmentDao.removeAttachment(attachment.getAttachmentId()))
        .thenReturn(attachment);

    MessageResponse messageResponse =
        attachmentService.removeAttachment(attachment.getAttachmentId());

    boolean isExistPreview = Files.exists(Paths.get(storagePath + attachment.getPreviewPath()));
    boolean isExistImage = Files.exists(Paths.get(storagePath + attachment.getFilePathInStorage()));

    Assert.assertTrue(!isExistPreview && !isExistImage && messageResponse.getCode() == 1);
  }
Ejemplo n.º 6
0
  @Test
  public void recruitersAreDisplayedByName() {
    Recruiter recruiter = Recruiter.named("George");
    RecruiterDisplayer recDisplayer = Mockito.mock(RecruiterDisplayer.class);
    recruiter.displayTo(recDisplayer);

    DisplayableName name = new Name("George");
    Mockito.verify(recDisplayer).displayRecruiter(name);
  }
Ejemplo n.º 7
0
 @Test
 public void recruiterCanPostJob() {
   Recruiter recruiter = Recruiter.named("George");
   Job developerJob = ATSJob.titled("Developer");
   JobRepository jobRepository = Mockito.mock(JobRepository.class);
   recruiter.post(developerJob).to(jobRepository);
   JobPosting posting = new JobPosting(recruiter, developerJob);
   Mockito.verify(jobRepository).add(posting);
 }
Ejemplo n.º 8
0
  @Test
  public void testGetUsersWithAuthority() throws SQLException {

    String expectedQuery =
        "select \"public\".\"users\".\"username\", \"public\".\"users\".\"locked\", \"public\".\"authorities\".\"authority\", count(\"public\".\"users\".\"username\") over () as \"count\" from \"public\".\"users\" join \"public\".\"authorities\" on \"public\".\"users\".\"username\" = \"public\".\"authorities\".\"username\" where \"public\".\"authorities\".\"authority\" = 'ROLE_ADMIN' order by \"public\".\"users\".\"username\" asc limit 5 offset 0";
    Pageable pageable = Mockito.mock(Pageable.class);

    ResultSet resultSet = Mockito.mock(ResultSet.class);

    Mockito.when(pageable.getPageNumber()).thenReturn(0);
    Mockito.when(pageable.getPageSize()).thenReturn(5);

    Mockito.when(resultSet.getInt(PagingConstants.COUNT)).thenReturn(1);
    Mockito.when(resultSet.getString("username")).thenReturn("admin");

    RESTPage<UserDTO> page = userDao.getUsersWithAuthority("ROLE_ADMIN", pageable);

    ArgumentCaptor<PagingRowCallbackHandler> pagingRowCallbackHandlerCaptor =
        ArgumentCaptor.forClass(PagingRowCallbackHandler.class);

    Mockito.verify(jdbcTemplate)
        .query(Matchers.eq(expectedQuery), pagingRowCallbackHandlerCaptor.capture());

    PagingRowCallbackHandler pagingRowCallbackHandler = pagingRowCallbackHandlerCaptor.getValue();

    pagingRowCallbackHandler.processRow(resultSet);

    Mockito.verify(resultSet).getInt(PagingConstants.COUNT);

    Mockito.verify(resultSet).getString("username");

    Assert.assertEquals(1, page.getContentSize());
    Assert.assertEquals("admin", page.getContent().get(0).getUsername());
  }
Ejemplo n.º 9
0
  @Test
  public void recruitersCanSeeJobseekersByJobAndDate() {
    setupRepositories();
    setupActors();
    JobPosting developerPosting = recruiter.post(developerJob).to(jobRepository);
    JobPosting architectPosting = recruiter.post(architectJob).to(jobRepository);

    TimeServer timeServerOne = Mockito.mock(TimeServer.class);
    TimeServer timeServerTwo = Mockito.mock(TimeServer.class);
    Date dayOne = null;
    Date dayTwo = null;
    try {
      dayOne = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2013-05-01 12:30:00");
      dayTwo = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2013-07-04 12:30:00");
    } catch (ParseException e) {
      fail();
    }
    Mockito.when(timeServerOne.getCurrentTime()).thenReturn(dayOne);
    Mockito.when(timeServerTwo.getCurrentTime()).thenReturn(dayTwo);
    ApplicationProcessor appProcessorOne = new ApplicationProcessor(appRepo, timeServerOne);
    ApplicationProcessor appProcessorTwo = new ApplicationProcessor(appRepo, timeServerTwo);

    boolean applyStatus;

    applyStatus = jobseekerTom.applyFor(developerPosting).to(appProcessorOne);
    assertTrue(applyStatus);
    applyStatus = jobseekerHarry.applyFor(developerPosting).to(appProcessorOne);
    assertTrue(applyStatus);
    applyStatus = jobseekerTom.applyFor(architectPosting).to(appProcessorTwo);
    assertTrue(applyStatus);
    applyStatus = jobseekerDick.applyFor(architectPosting).to(appProcessorTwo);
    assertTrue(applyStatus);

    Applications appsOnDayOne = recruiter.getApplications().filterBy(dayOne).from(appRepo);

    ApplicationsDisplayer appsDisplayer = Mockito.mock(ApplicationsDisplayer.class);
    appsOnDayOne.displayTo(appsDisplayer);
    Mockito.verify(appsDisplayer)
        .displayApplications(Mockito.argThat(new SetOfTwoAppsWithDates(dayOne)));

    Applications appsOnDayTwoForArchitect =
        recruiter.getApplications().filterBy(architectPosting).filterBy(dayTwo).from(appRepo);

    appsDisplayer = Mockito.mock(ApplicationsDisplayer.class);
    appsOnDayTwoForArchitect.displayTo(appsDisplayer);
    Mockito.verify(appsDisplayer)
        .displayApplications(
            Mockito.argThat(new SetOfTwoAppsWithJobPostingsAndDates(dayTwo, architectPosting)));
  }
Ejemplo n.º 10
0
  @Test
  public void testGetUsersWithAuthority_page2() {

    String expectedQuery =
        "select \"public\".\"users\".\"username\", \"public\".\"users\".\"locked\", \"public\".\"authorities\".\"authority\", count(\"public\".\"users\".\"username\") over () as \"count\" from \"public\".\"users\" join \"public\".\"authorities\" on \"public\".\"users\".\"username\" = \"public\".\"authorities\".\"username\" where \"public\".\"authorities\".\"authority\" = 'ROLE_ADMIN' order by \"public\".\"users\".\"username\" asc limit 5 offset 5";
    Pageable pageable = Mockito.mock(Pageable.class);

    Mockito.when(pageable.getPageNumber()).thenReturn(1);
    Mockito.when(pageable.getPageSize()).thenReturn(5);

    userDao.getUsersWithAuthority("ROLE_ADMIN", pageable);

    Mockito.verify(jdbcTemplate)
        .query(Matchers.eq(expectedQuery), Matchers.any(PagingRowCallbackHandler.class));
  }
Ejemplo n.º 11
0
  @Test
  @PrepareForTest({UtilsHibernate.class})
  public void testGetArticles() throws Exception {

    PowerMockito.mockStatic(UtilsHibernate.class);

    List<Article> articleList = new ArrayList<>();

    Article article1 = new Article();
    article1.setTitle("article1");
    articleList.add(article1);

    Article article2 = new Article();
    article2.setTitle("article2");
    articleList.add(article2);

    Mockito.when(
            articleDao.getAllArticles(
                2, 1, UtilsHibernate.getOrderByString("asc", "title"), "title", 1))
        .thenReturn(articleList);

    List<Article> articles = articleService.getArticles(2, 1, "asc", "title", 1);

    Assert.assertTrue(
        articles.get(0).getTitle().equals("article1")
            && articles.get(1).getTitle().equals("article2"));
  }
  @Test
  public void testLoadEventsWithDecorators() {
    UUID identifier = UUID.randomUUID();
    SpyEventPreprocessor decorator1 = new SpyEventPreprocessor();
    SpyEventPreprocessor decorator2 = new SpyEventPreprocessor();
    testSubject.setEventStreamDecorators(Arrays.asList(decorator1, decorator2));
    when(mockEventStore.readEvents("test", identifier))
        .thenReturn(
            new SimpleDomainEventStream(
                new GenericDomainEventMessage<String>(
                    identifier, (long) 1, "Mock contents", MetaData.emptyInstance()),
                new GenericDomainEventMessage<String>(
                    identifier, (long) 2, "Mock contents", MetaData.emptyInstance()),
                new GenericDomainEventMessage<String>(
                    identifier, (long) 3, "Mock contents", MetaData.emptyInstance())));
    TestAggregate aggregate = testSubject.load(identifier);
    // loading them in...
    InOrder inOrder = Mockito.inOrder(decorator1.lastSpy, decorator2.lastSpy);
    inOrder.verify(decorator2.lastSpy).next();
    inOrder.verify(decorator1.lastSpy).next();

    inOrder.verify(decorator2.lastSpy).next();
    inOrder.verify(decorator1.lastSpy).next();

    inOrder.verify(decorator2.lastSpy).next();
    inOrder.verify(decorator1.lastSpy).next();
    aggregate.apply(new StubDomainEvent());
    aggregate.apply(new StubDomainEvent());
  }
  @Test
  public void setConfigurationOK() throws Exception {

    // Mock the task scheduler and capture the runnable
    ArgumentCaptor<Runnable> runnableArg = ArgumentCaptor.forClass(Runnable.class);
    when(taskScheduler.scheduleWithFixedDelay(runnableArg.capture(), anyLong()))
        .thenReturn(Mockito.mock(ScheduledFuture.class));

    // Mock the response to the subsribeContext
    ArgumentCaptor<SuccessCallback> successArg = ArgumentCaptor.forClass(SuccessCallback.class);
    ListenableFuture<SubscribeContextResponse> responseFuture =
        Mockito.mock(ListenableFuture.class);
    doNothing().when(responseFuture).addCallback(successArg.capture(), any());

    Configuration configuration = getBasicConf();
    subscriptionManager.setConfiguration(configuration);

    // Capture the arg of subscription and return the mocked future
    ArgumentCaptor<String> urlProviderArg = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<SubscribeContext> subscribeContextArg =
        ArgumentCaptor.forClass(SubscribeContext.class);
    when(ngsiClient.subscribeContext(
            urlProviderArg.capture(), eq(null), subscribeContextArg.capture()))
        .thenReturn(responseFuture);

    // Execute scheduled runnable
    runnableArg.getValue().run();

    // Return the SubscribeContextResponse
    callSuccessCallback(successArg);

    SubscribeContext subscribeContext = subscribeContextArg.getValue();
    assertEquals("S.*", subscribeContext.getEntityIdList().get(0).getId());
    assertEquals("TempSensor", subscribeContext.getEntityIdList().get(0).getType());
    assertEquals(true, subscribeContext.getEntityIdList().get(0).getIsPattern());
    assertEquals("temp", subscribeContext.getAttributeList().get(0));
    assertEquals("PT1H", subscribeContext.getDuration());
    assertEquals("http://iotAgent", urlProviderArg.getValue());

    Set<Provider> providers = configuration.getEventTypeIns().get(0).getProviders();
    for (Provider provider : providers) {
      assertEquals("12345678", provider.getSubscriptionId());
      assertNotNull(provider.getSubscriptionDate());
    }
  }
Ejemplo n.º 14
0
  @Test
  public void recruitersCanDisplayJobsTheyPosted() {
    setupActors();
    JobRepository jobRepository = new JobRepository();

    JobPosting developerPosting = recruiter.post(developerJob).to(jobRepository);
    JobPosting architectPosting = recruiter.post(architectJob).to(jobRepository);
    JobPosting programmerPosting = recruiter.post(programmerJob).to(jobRepository);

    JobPostings jobPostings = recruiter.getPostedJobs().from(jobRepository);

    JobPostingsDisplayer postingsDisplayer = Mockito.mock(JobPostingsDisplayer.class);
    jobPostings.displayTo(postingsDisplayer);
    Mockito.verify(postingsDisplayer)
        .displayJobPostings(
            Matchers.argThat(
                new SetOfThreeJobPostings(developerPosting, architectPosting, programmerPosting)));
  }
 @Test
 public void testInvalideSubscription() {
   // Mock future for unsubscribeContext
   ListenableFuture<UnsubscribeContextResponse> responseFuture =
       Mockito.mock(ListenableFuture.class);
   doNothing().when(responseFuture).addCallback(any(), any());
   when(ngsiClient.unsubscribeContext(eq("http://iotAgent"), eq(null), eq("9999")))
       .thenReturn(responseFuture);
   subscriptionManager.validateSubscriptionId("9999", "http://iotAgent");
 }
Ejemplo n.º 16
0
  @Test
  public void enrollStudentTest() throws StudentException, ServiceException, PaymentException {

    Mockito.when(
            studentController.newStudent(
                "Ana Julia Costa",
                cpf,
                rg,
                date,
                email,
                address,
                phone1,
                phone2,
                "Maria Julia",
                "Julio Costa"))
        .thenReturn(studentMock);
    Mockito.when(serviceController.newService(studentMock, courses, packages, value))
        .thenReturn(serviceMock);
    Mockito.when(paymentController.newPayment(serviceMock, 1, 1, 1)).thenReturn(paymentMock);

    try {
      enrollController.enrollStudent(
          "Ana Julia Costa",
          cpf,
          rg,
          date,
          email,
          address,
          phone1,
          phone2,
          "Maria Julia",
          "Julio Costa",
          courses,
          packages,
          1,
          1,
          2,
          value);
    } catch (StudentException | ServiceException | PaymentException e) {
      fail("Should not throw this exception: " + e.getMessage());
    }
  }
  @Test
  public void testUnsubscribeOnProviderRemoval() {

    // Mock the task scheduler and capture the runnable
    ArgumentCaptor<Runnable> runnableArg = ArgumentCaptor.forClass(Runnable.class);
    when(taskScheduler.scheduleWithFixedDelay(runnableArg.capture(), anyLong()))
        .thenReturn(Mockito.mock(ScheduledFuture.class));

    // Mock the response to the subsribeContext
    ArgumentCaptor<SuccessCallback> successArg = ArgumentCaptor.forClass(SuccessCallback.class);
    ListenableFuture<SubscribeContextResponse> responseFuture =
        Mockito.mock(ListenableFuture.class);
    doNothing().when(responseFuture).addCallback(successArg.capture(), any());

    // Return the mocked future on subscription
    when(ngsiClient.subscribeContext(any(), any(), any())).thenReturn(responseFuture);

    Configuration configuration = getBasicConf();
    subscriptionManager.setConfiguration(configuration);

    // Execute scheduled runnable
    runnableArg.getValue().run();

    // Return the SubscribeContextResponse
    callSuccessCallback(successArg);

    // Mock future for unsubscribeContext
    ListenableFuture<UnsubscribeContextResponse> responseFuture2 =
        Mockito.mock(ListenableFuture.class);
    doNothing().when(responseFuture2).addCallback(successArg.capture(), any());
    when(ngsiClient.unsubscribeContext(eq("http://iotAgent"), eq(null), eq("12345678")))
        .thenReturn(responseFuture2);

    // Reset conf should trigger unsubsribeContext
    Configuration emptyConfiguration = getBasicConf();
    emptyConfiguration.getEventTypeIns().get(0).setProviders(Collections.emptySet());
    subscriptionManager.setConfiguration(emptyConfiguration);

    // Check that unsubsribe is called
    Assert.notNull(successArg.getValue());
  }
Ejemplo n.º 18
0
  @Test
  public void testUpdateArticle() throws Exception {

    Article article = new Article();
    article.setTitle("test");

    Mockito.when(articleDao.updateArticle(article)).thenReturn(article);

    Article articleResult = articleService.updateArticle(article);

    Assert.assertEquals(articleResult, article);
  }
Ejemplo n.º 19
0
  @Test
  public void testGetArticle() throws Exception {

    Article article = new Article();
    article.setArticleId(1);
    article.setTitle("test title");

    Mockito.when(articleDao.getArticle(article)).thenReturn(article);

    Article responseArticle = articleService.getArticle(article);

    Assert.assertEquals(article.getArticleId(), responseArticle.getArticleId());
  }
Ejemplo n.º 20
0
  @Test
  public void testGetArticlesByUser() throws Exception {

    Article article = new Article();
    article.setArticleId(1);
    article.setTitle("test title");

    List<Article> articles = new ArrayList<>();
    articles.add(article);

    Mockito.when(articleDao.getArticlesByUserOwner(user)).thenReturn(articles);

    List<Article> responseArticles = articleService.getArticlesByUser(user);

    Assert.assertEquals(responseArticles.get(0).getArticleId(), 1);
  }
  @Test
  public void testSaveEventsWithDecorators() {
    SpyEventPreprocessor decorator1 = new SpyEventPreprocessor();
    SpyEventPreprocessor decorator2 = new SpyEventPreprocessor();
    testSubject.setEventStreamDecorators(Arrays.asList(decorator1, decorator2));
    testSubject.setEventStore(
        new EventStore() {
          @Override
          public void appendEvents(String type, DomainEventStream events) {
            while (events.hasNext()) {
              events.next();
            }
          }

          @Override
          public DomainEventStream readEvents(String type, Object identifier) {
            return mockEventStore.readEvents(type, identifier);
          }
        });
    UUID identifier = UUID.randomUUID();
    when(mockEventStore.readEvents("test", identifier))
        .thenReturn(
            new SimpleDomainEventStream(
                new GenericDomainEventMessage<String>(
                    identifier, (long) 3, "Mock contents", MetaData.emptyInstance())));
    TestAggregate aggregate = testSubject.load(identifier);
    aggregate.apply(new StubDomainEvent());
    aggregate.apply(new StubDomainEvent());

    CurrentUnitOfWork.commit();

    InOrder inOrder = Mockito.inOrder(decorator1.lastSpy, decorator2.lastSpy);
    inOrder.verify(decorator1.lastSpy).next();
    inOrder.verify(decorator2.lastSpy).next();

    inOrder.verify(decorator1.lastSpy).next();
    inOrder.verify(decorator2.lastSpy).next();
  }
Ejemplo n.º 22
0
  /**
   * Check creating new article with get user auth context
   *
   * @throws Exception
   */
  @Test
  @PrepareForTest({SecurityContextHolder.class})
  public void testCreateArticle() throws Exception {

    Article article = new Article();

    PowerMockito.mockStatic(SecurityContextHolder.class);

    PowerMockito.when(SecurityContextHolder.getContext()).thenReturn(securityContext);
    Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
    Mockito.when(authentication.getPrincipal()).thenReturn(userDetail);

    Mockito.when(userDetail.getUsername()).thenReturn("userName");
    Mockito.when(userService.getAuthorizedUser()).thenReturn(user);

    articleService.createArticle(article);

    ArgumentCaptor<Article> argument = ArgumentCaptor.forClass(Article.class);
    Mockito.verify(articleDao, Mockito.times(1)).createArticle(argument.capture());

    Assert.assertEquals(argument.getValue().getUserOwner(), user);
  }
Ejemplo n.º 23
0
  @Test
  public void recruitersCanSeeJobseekersByJob() {
    setupActors();
    setupRepositories();

    JobPosting developerPosting = recruiter.post(developerJob).to(jobRepository);
    JobPosting architectPosting = recruiter.post(architectJob).to(jobRepository);

    boolean applyStatus;
    applyStatus = jobseekerTom.applyFor(developerPosting).to(appProcessor);
    assertTrue(applyStatus);
    applyStatus = jobseekerHarry.applyFor(developerPosting).to(appProcessor);
    assertTrue(applyStatus);
    applyStatus = jobseekerTom.applyFor(architectPosting).to(appProcessor);
    assertTrue(applyStatus);
    applyStatus = jobseekerDick.applyFor(architectPosting).to(appProcessor);
    assertTrue(applyStatus);

    Applications developerApps =
        recruiter.getApplications().filterBy(developerPosting).from(appRepo);

    ApplicationsDisplayer appsDisplayer = Mockito.mock(ApplicationsDisplayer.class);
    developerApps.displayTo(appsDisplayer);
    Mockito.verify(appsDisplayer)
        .displayApplications(
            Mockito.argThat(new SetOfTwoAppsWithJobSeekers(jobseekerTom, jobseekerHarry)));

    Applications architectApps =
        recruiter.getApplications().filterBy(architectPosting).from(appRepo);

    appsDisplayer = Mockito.mock(ApplicationsDisplayer.class);
    architectApps.displayTo(appsDisplayer);
    Mockito.verify(appsDisplayer)
        .displayApplications(
            Mockito.argThat(new SetOfTwoAppsWithJobSeekers(jobseekerTom, jobseekerDick)));
  }
/** Tests for SubscriptionManager */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class SubscriptionManagerTest {

  @Mock TaskScheduler taskScheduler;

  @Mock NgsiClient ngsiClient = Mockito.mock(NgsiClient.class, RETURNS_SMART_NULLS);

  @Autowired @InjectMocks SubscriptionManager subscriptionManager;

  @Before
  public void setUp() throws URISyntaxException {
    MockitoAnnotations.initMocks(this);
  }

  @After
  public void after() {
    reset(ngsiClient);
    reset(taskScheduler);
  }

  @Test
  public void setConfigurationOK() throws Exception {

    // Mock the task scheduler and capture the runnable
    ArgumentCaptor<Runnable> runnableArg = ArgumentCaptor.forClass(Runnable.class);
    when(taskScheduler.scheduleWithFixedDelay(runnableArg.capture(), anyLong()))
        .thenReturn(Mockito.mock(ScheduledFuture.class));

    // Mock the response to the subsribeContext
    ArgumentCaptor<SuccessCallback> successArg = ArgumentCaptor.forClass(SuccessCallback.class);
    ListenableFuture<SubscribeContextResponse> responseFuture =
        Mockito.mock(ListenableFuture.class);
    doNothing().when(responseFuture).addCallback(successArg.capture(), any());

    Configuration configuration = getBasicConf();
    subscriptionManager.setConfiguration(configuration);

    // Capture the arg of subscription and return the mocked future
    ArgumentCaptor<String> urlProviderArg = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<SubscribeContext> subscribeContextArg =
        ArgumentCaptor.forClass(SubscribeContext.class);
    when(ngsiClient.subscribeContext(
            urlProviderArg.capture(), eq(null), subscribeContextArg.capture()))
        .thenReturn(responseFuture);

    // Execute scheduled runnable
    runnableArg.getValue().run();

    // Return the SubscribeContextResponse
    callSuccessCallback(successArg);

    SubscribeContext subscribeContext = subscribeContextArg.getValue();
    assertEquals("S.*", subscribeContext.getEntityIdList().get(0).getId());
    assertEquals("TempSensor", subscribeContext.getEntityIdList().get(0).getType());
    assertEquals(true, subscribeContext.getEntityIdList().get(0).getIsPattern());
    assertEquals("temp", subscribeContext.getAttributeList().get(0));
    assertEquals("PT1H", subscribeContext.getDuration());
    assertEquals("http://iotAgent", urlProviderArg.getValue());

    Set<Provider> providers = configuration.getEventTypeIns().get(0).getProviders();
    for (Provider provider : providers) {
      assertEquals("12345678", provider.getSubscriptionId());
      assertNotNull(provider.getSubscriptionDate());
    }
  }

  @Test
  public void testUnsubscribeOnEventTypeRemoval() {

    // Mock the task scheduler and capture the runnable
    ArgumentCaptor<Runnable> runnableArg = ArgumentCaptor.forClass(Runnable.class);
    when(taskScheduler.scheduleWithFixedDelay(runnableArg.capture(), anyLong()))
        .thenReturn(Mockito.mock(ScheduledFuture.class));

    // Mock the response to the subsribeContext
    ArgumentCaptor<SuccessCallback> successArg = ArgumentCaptor.forClass(SuccessCallback.class);
    ListenableFuture<SubscribeContextResponse> responseFuture =
        Mockito.mock(ListenableFuture.class);
    doNothing().when(responseFuture).addCallback(successArg.capture(), any());

    // Return the mocked future on subscription
    when(ngsiClient.subscribeContext(any(), any(), any())).thenReturn(responseFuture);

    Configuration configuration = getBasicConf();
    subscriptionManager.setConfiguration(configuration);

    // Execute scheduled runnable
    runnableArg.getValue().run();

    // Return the SubscribeContextResponse
    callSuccessCallback(successArg);

    // Mock future for unsubscribeContext
    ListenableFuture<UnsubscribeContextResponse> responseFuture2 =
        Mockito.mock(ListenableFuture.class);
    doNothing().when(responseFuture2).addCallback(successArg.capture(), any());
    when(ngsiClient.unsubscribeContext(eq("http://iotAgent"), eq(null), eq("12345678")))
        .thenReturn(responseFuture2);

    // Set a configuration without the eventType
    Configuration emptyConfiguration = new Configuration();
    emptyConfiguration.setEventTypeIns(Collections.emptyList());
    subscriptionManager.setConfiguration(emptyConfiguration);

    // Check that unsubsribe is called when a later configuration removed the event type
    Assert.notNull(successArg.getValue());
  }

  @Test
  public void testUnsubscribeOnProviderRemoval() {

    // Mock the task scheduler and capture the runnable
    ArgumentCaptor<Runnable> runnableArg = ArgumentCaptor.forClass(Runnable.class);
    when(taskScheduler.scheduleWithFixedDelay(runnableArg.capture(), anyLong()))
        .thenReturn(Mockito.mock(ScheduledFuture.class));

    // Mock the response to the subsribeContext
    ArgumentCaptor<SuccessCallback> successArg = ArgumentCaptor.forClass(SuccessCallback.class);
    ListenableFuture<SubscribeContextResponse> responseFuture =
        Mockito.mock(ListenableFuture.class);
    doNothing().when(responseFuture).addCallback(successArg.capture(), any());

    // Return the mocked future on subscription
    when(ngsiClient.subscribeContext(any(), any(), any())).thenReturn(responseFuture);

    Configuration configuration = getBasicConf();
    subscriptionManager.setConfiguration(configuration);

    // Execute scheduled runnable
    runnableArg.getValue().run();

    // Return the SubscribeContextResponse
    callSuccessCallback(successArg);

    // Mock future for unsubscribeContext
    ListenableFuture<UnsubscribeContextResponse> responseFuture2 =
        Mockito.mock(ListenableFuture.class);
    doNothing().when(responseFuture2).addCallback(successArg.capture(), any());
    when(ngsiClient.unsubscribeContext(eq("http://iotAgent"), eq(null), eq("12345678")))
        .thenReturn(responseFuture2);

    // Reset conf should trigger unsubsribeContext
    Configuration emptyConfiguration = getBasicConf();
    emptyConfiguration.getEventTypeIns().get(0).setProviders(Collections.emptySet());
    subscriptionManager.setConfiguration(emptyConfiguration);

    // Check that unsubsribe is called
    Assert.notNull(successArg.getValue());
  }

  @Test
  public void testInvalideSubscription() {
    // Mock future for unsubscribeContext
    ListenableFuture<UnsubscribeContextResponse> responseFuture =
        Mockito.mock(ListenableFuture.class);
    doNothing().when(responseFuture).addCallback(any(), any());
    when(ngsiClient.unsubscribeContext(eq("http://iotAgent"), eq(null), eq("9999")))
        .thenReturn(responseFuture);
    subscriptionManager.validateSubscriptionId("9999", "http://iotAgent");
  }

  @Test
  public void testValidSubscription() {
    // add configuration
    // Mock the task scheduler and capture the runnable
    ArgumentCaptor<Runnable> runnableArg = ArgumentCaptor.forClass(Runnable.class);
    when(taskScheduler.scheduleWithFixedDelay(runnableArg.capture(), anyLong()))
        .thenReturn(Mockito.mock(ScheduledFuture.class));

    // Mock the response to the subsribeContext
    ArgumentCaptor<SuccessCallback> successArg = ArgumentCaptor.forClass(SuccessCallback.class);
    ListenableFuture<SubscribeContextResponse> responseFuture =
        Mockito.mock(ListenableFuture.class);
    doNothing().when(responseFuture).addCallback(successArg.capture(), any());

    Configuration configuration = getBasicConf();
    subscriptionManager.setConfiguration(configuration);

    // Capture the arg of subscription and return the mocked future
    ArgumentCaptor<String> urlProviderArg = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<SubscribeContext> subscribeContextArg =
        ArgumentCaptor.forClass(SubscribeContext.class);
    when(ngsiClient.subscribeContext(
            urlProviderArg.capture(), eq(null), subscribeContextArg.capture()))
        .thenReturn(responseFuture);

    // Execute scheduled runnable
    runnableArg.getValue().run();

    // Return the SubscribeContextResponse
    callSuccessCallback(successArg);

    // check ngsiClient.unsubscribe() is never called
    verify(ngsiClient, never()).unsubscribeContext(any(), any(), any());
    subscriptionManager.validateSubscriptionId("12345678", "http://iotAgent");
  }

  private void callSuccessCallback(ArgumentCaptor<SuccessCallback> successArg) {
    SubscribeContextResponse response = new SubscribeContextResponse();
    SubscribeResponse subscribeResponse = new SubscribeResponse();
    subscribeResponse.setSubscriptionId("12345678");
    subscribeResponse.setDuration("PT1H");
    response.setSubscribeResponse(subscribeResponse);
    successArg.getValue().onSuccess(response);
  }
}
Ejemplo n.º 25
0
 @Before
 public void init() {
   Mockito.when(databaseProperties.getJooqDialect()).thenReturn("POSTGRES_9_3");
 }
Ejemplo n.º 26
0
public class QuestHouseTest {

  QuestRoom mockRoom = Mockito.mock(QuestRoom.class); // A mocked QuestRoom

  // 0================================================================0
  // |                    NEW QUEST BUILDING TESTS                    |
  // 0================================================================0

  /**
   * Tests that a new QuestBuilding object will return null if you try to get its initial QuestRoom
   * object.
   */
  @Test
  public void testEmptyInitialRoom() {
    QuestHouse houseOfRooms = new QuestHouse();
    assertNull(houseOfRooms.getInitialRoom()); // Asserts that the initial room is null
  }

  /** Tests that a new QuestBuilding object will start with zero rooms. */
  @Test
  public void testZeroStartingRooms() {
    QuestHouse houseOfRooms = new QuestHouse();
    int numRooms = houseOfRooms.getNumberOfRooms();
    assertEquals(0, numRooms); // Asserts that the initial number of rooms is zero
  }

  // 0================================================================0
  // |                       INITIAL ROOM TESTS                       |
  // 0================================================================0

  /**
   * Tests that setting the initial room of a QuestBuilding object with a non-null QuestRoom object
   * will return a non-null QuestRoom object. This is not a particularly good test but it does show
   * that an initial room will be set to something other than null.
   */
  @Test
  public void testSetInitialRoom() {
    QuestHouse houseOfRooms = new QuestHouse();
    houseOfRooms.setInitialRoom(mockRoom);
    assertNotNull(houseOfRooms.getInitialRoom()); // Asserts that the initial room is not null
  }

  /**
   * Tests that incrementing the number of rooms by a specific amount will return the same amount
   * when getNumberOfRooms is called.
   */
  @Test
  public void testIncrementNumberOfRooms() {
    QuestHouse houseOfRooms = new QuestHouse();
    int numLoops = 5;
    for (int i = 0; i < numLoops; i++) {
      houseOfRooms.incrementNumberOfRooms();
    }
    assertEquals(
        numLoops,
        houseOfRooms
            .getNumberOfRooms()); // Asserts that the number of rooms returned matches the loop
                                  // amount
  }

  /** Tests that the initial QuestRoom returned is the same as the initial QuestRoom that is set. */
  @Test
  public void testSameInitialRoom() {
    QuestHouse houseOfRooms = new QuestHouse();
    houseOfRooms.setInitialRoom(mockRoom);
    assertSame(
        mockRoom, houseOfRooms.getInitialRoom()); // Asserts that the QuestRoom objects are the same
  }
}