Skip to content

Commit

Permalink
allow adding the verify to the expects chain
Browse files Browse the repository at this point in the history
  • Loading branch information
ryber committed Dec 10, 2023
1 parent 6ea3e91 commit f298362
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -112,4 +112,6 @@ public interface Expectation {
void verify();

void verify(Times times);

Expectation times(Times never);
}
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ public ExpectedResponse thenReturn(Supplier<String> supplier){

@Override
public void verify() {
verify(Times.atLeastOnce());
verify(null);
}

@Override
Expand Down
14 changes: 11 additions & 3 deletions unirest-mocks/src/main/java/kong/unirest/core/Invocation.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ class Invocation implements Expectation {
private MatchStatus expectedBodyStatus;
private ExpectedResponseRecord expectedResponse = new ExpectedResponseRecord(this);
private Function<HttpRequest<?>, ExpectedResponse> functionalResponse = r -> expectedResponse;
private Times expectedTimes = Times.atLeastOnce();

public Invocation(Routes routes){
this.routes = routes;
Expand Down Expand Up @@ -144,19 +145,26 @@ public ExpectedResponse thenReturn() {

@Override
public void verify() {
verify(Times.atLeastOnce());
verify(null);
}

@Override
public void verify(Times times) {
Times.EvaluationResult match = times.matches(requests.size());
var thisTime = times == null ? expectedTimes : times;
var match = thisTime.matches(requests.size());
if(!match.isSuccess()){
throw new UnirestAssertion("%s\n%s", match.getMessage(), details());
}
}

@Override
public Expectation times(Times times) {
this.expectedTimes = times;
return this;
}

private String details() {
StringBuilder sb = new StringBuilder(routes.getMethod().name())
var sb = new StringBuilder(routes.getMethod().name())
.append(" ")
.append(routes.getPath()).append(lineSeparator());
if(expectedHeaders.size() > 0){
Expand Down
13 changes: 13 additions & 0 deletions unirest-mocks/src/test/java/kong/tests/VerifyTimesTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -134,4 +134,17 @@ void verifyAtMost() {

Unirest.get(path).asEmpty();
}

@Test
void buildExpectationTimesIntoChain() {
var expect = client.expect(GET, path).times(Times.never()).thenReturn("hi");

assertDoesNotThrow(() -> expect.verify());

Unirest.get(path).asEmpty();

var ex = assertThrows(UnirestAssertion.class, () -> expect.verify());
assertEquals("Expected exactly 0 invocations but got 1\n" +
"GET http://basic\n", ex.getMessage());
}
}

0 comments on commit f298362

Please sign in to comment.