Hamcrest matcher for a sublist/partial match?

醉酒当歌 提交于 2021-02-07 08:19:53

问题


Say I have an actual List [1, 2, 3, 4] and I want to check if it contains the sub-list [2, 3] (i.e. order is also important). Is there an existing matcher that does this?

(There's a poorly-named hasItems method which only checks the actual list matches any one item in the expected list....)


回答1:


Write your own if you can.

see Writing custom matchers

It should be something like:

 public class HasSublist<T> extends TypeSafeMatcher<T> {

     @Override
      public boolean matchesSafely(List<T> subList) {
        //Logic if sublist exist ...
        return true;
      }

      public static <T> Matcher<T> hasSubList(List<T> containsSublist) {
        return new HasSublist<T>(containsSublist);
      }
}



回答2:


I think there is no such predefined Matcher. I'm using AssertJ on top of JUnit so I can address this case like this:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.assertj.core.api.Assertions;
import org.junit.Test;

public class TestContains2 {

  @Test
  public void test_contains() {
    List<Integer> a = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
    Assertions
      .assertThat(a)
      .containsSequence(2, 3);
  }
}


来源:https://stackoverflow.com/questions/34589894/hamcrest-matcher-for-a-sublist-partial-match

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!