diff --git a/unirest-modules-mocks/src/main/java/kong/unirest/core/Routes.java b/unirest-modules-mocks/src/main/java/kong/unirest/core/Routes.java index 8a8e58deb..ff24280a5 100644 --- a/unirest-modules-mocks/src/main/java/kong/unirest/core/Routes.java +++ b/unirest-modules-mocks/src/main/java/kong/unirest/core/Routes.java @@ -93,20 +93,38 @@ private Optional getBestMatch(HttpRequest request) { } private Optional getBestMatch(HttpRequest request, boolean expected) { - Map map = new TreeMap<>(); - invokes.stream() - .forEach(i -> { - Integer score = i.scoreMatch(request); - if(score >= 0) { - map.put(score, i); - } - }); - if (map.size() == 0) { + Invocation best = null; + int bestScore = -1; + + for (Invocation invocation : invokes) { + if (!invocation.isExpected().equals(expected)) { + continue; + } + + int score = invocation.scoreMatch(request); + + if (score < 0) { + continue; + } + + if (score > bestScore) { + best = invocation; + bestScore = score; + } else if (score == bestScore + && expected + && best != null + && best.requestSize() > 0 + && invocation.requestSize() == 0) { + best = invocation; + } + } + + if (best == null) { return Optional.empty(); } - Invocation value = map.get(Collections.max(map.keySet())); - value.log(request); - return Optional.of(value); + + best.log(request); + return Optional.of(best); } @Override diff --git a/unirest-modules-mocks/src/test/java/kong/tests/MultipleExpectsTest.java b/unirest-modules-mocks/src/test/java/kong/tests/MultipleExpectsTest.java index e28b61994..651fa2eef 100644 --- a/unirest-modules-mocks/src/test/java/kong/tests/MultipleExpectsTest.java +++ b/unirest-modules-mocks/src/test/java/kong/tests/MultipleExpectsTest.java @@ -94,7 +94,7 @@ void willPickTheBestMatchingQueryExpectation() { } @Test - void whenDuplicateExpectsExistUseTheLastOne() { + void whenDuplicateExpectsExistUseThemInOrder() { client.expect(GET, path) .queryString("monster", "grover") .thenReturn("one"); @@ -103,17 +103,19 @@ void whenDuplicateExpectsExistUseTheLastOne() { .queryString("monster", "grover") .thenReturn("two"); - String result = Unirest.get(path) + String first = Unirest.get(path) .queryString("monster", "grover") .asString() .getBody(); - assertEquals("two", result); + String second = Unirest.get(path) + .queryString("monster", "grover") + .asString() + .getBody(); - assertException(() -> client.verifyAll(), - "Expected at least 1 invocations but got 0\n" + - "GET http://basic\n" + - "Params:\n" + - "monster: grover"); + assertEquals("one", first); + assertEquals("two", second); + + client.verifyAll(); } }