【问题标题】:How to write Matchers that match Matchers matching stuff如何编写匹配匹配器的匹配器匹配的东西
【发布时间】:2013-07-30 08:50:14
【问题描述】:

好的,所以我想测试我闪亮的新 hamcrest Matchers。

是否有任何匹配器匹配自定义匹配器匹配或不匹配的东西? 这将极大地帮助编写自定义匹配器的测试。

【问题讨论】:

  • 如果你多用“matcher”这个词,可能会更清楚。

标签: java unit-testing junit hamcrest


【解决方案1】:

在我看来,您的Matcher 不需要Matcher。您应该编写一个单元测试并使用您的Matcher

 @Test
 public void testPass(){
    assertThat(input, myMatcher);
 }


 @Test
 public void testFail(){
    assertThat(input, not(myMatcher));
 }

对所有需要测试的情况重复冲洗。

【讨论】:

    【解决方案2】:

    您可以使用 org.mockito.Matchers 类来存根您的输入。此类公开了许多方法来使用您的存根。

    • Matchers.anyString()
    • Matchers.anyInt() 等等。

    假设你在 A 类中有一个函数

    class A{
    
    public void loadFile(){
     file = new FileInputStream("/test/webapps/test.properties");
    ...
    ....
    }
    

    如果你想写一个测试用例,你必须使用 Matchers 类进行存根编写如下-

    class Atest{
    @Test
        public void testLoadFile()
           {
               final FileInputStream fileInputStreamMock = PowerMockito.mock(FileInputStream.class);
              PowerMockito.whenNew(FileInputStream.class).withArguments(Matchers.anyString())
                                  .thenReturn(fileInputStreamMock);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多