コード例 #1
0
  @Test // Uses of JMockit API: 3
  public void returningElementsFromAList() {
    final List<String> list = asList("a", "b", "c");

    new Expectations() {
      {
        mockedList.get(anyInt);
        result = list;
      }
    };

    assertEquals("a", mockedList.get(0));
    assertEquals("b", mockedList.get(1));
    assertEquals("c", mockedList.get(2));
    assertEquals("c", mockedList.get(3));
  }
コード例 #2
0
  @Test // Uses of JMockit API: 8
  public void useArgumentMatchers() {
    new Expectations() {
      {
        // Using built-in matchers:
        mockedList.get(anyInt);
        result = "element";

        // Using Hamcrest matchers:
        mockedList.get(withArgThat(is(equalTo(5))));
        result = new IllegalArgumentException();
        minTimes = 0;
        mockedList.contains(withArgThat(hasProperty("bytes")));
        result = true;
        mockedList.containsAll(withArgThat(hasSize(2)));
        result = true;
      }
    };

    assertEquals("element", mockedList.get(999));
    assertTrue(mockedList.contains("abc"));
    assertTrue(mockedList.containsAll(asList("a", "b")));

    new Verifications() {
      {
        mockedList.get(anyInt);
      }
    };
  }
コード例 #3
0
  @Test // Uses of JMockit API: 3
  public void stubAndVerifyInvocationWithoutRepeatingItInExpectationAndVerificationBlocks() {
    new Expectations() {
      {
        // Notice that this can't be done in Mockito, which requires the repetition of
        // "mockedList.get(0);" in the verification phase.
        mockedList.get(0);
        result = "first";
        times = 1;
      }
    };

    assertEquals("first", mockedList.get(0));
  }
コード例 #4
0
  @Test // Uses of JMockit API: 3
  public void stubAndVerifyInvocation() {
    // A recorded expectation is expected to occur at least once, by default.
    new Expectations() {
      {
        mockedList.get(0);
        result = "first";
      }
    };

    assertEquals("first", mockedList.get(0));

    // Note that verifying a stubbed invocation isn't "just redundant" if the test cares that the
    // invocation occurs at least once. If this is the case, then it's not safe to expect the test
    // to break without an explicit verification, because the method under test may never call the
    // stubbed one, and that would be a bug that the test should detect.
  }