簡體   English   中英

如何模擬Spring bean及其自動裝配的ctor參數?

[英]How to mock a spring bean and also its autowired ctor arguments?

我想模擬一個對象及其自動裝配的構造函數依賴項之一。

例如:

class MyTest {
  @MockBean A a;
  @Test myTest() {
    assertTrue(when(a.some()).thenCallRealMethod());
  }
}
@Component
class A {
  private B b;
  A(B dependency) {
    this.b = dependency;
  }
  boolean some() {
    return b.value();
  }
}
@Configuration
class B {
  boolean value() { return true; }
}

當在MyTest::myTest調用a::some時,這將引發NPE。 如何模擬模擬依賴項?

首先,您必須選擇跑步者

SpringRunner或Mockito Runner

在這種情況下,我選擇了SpringRunner:Docs: https ://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/context/junit4/SpringRunner.html

然后創建一個A的MockBean,並且必須定義模擬行為

when(a.some()).thenReturn(true);

@RunWith(SpringRunner.class)
    public class MyTest {

         @MockBean A a;

         @Test
         public void  myTest() {
            when(a.some()).thenReturn(true);
            assertTrue(a.some());

        }
        @Component
        class A {
          private B b;
          A(B dependency) {
            this.b = dependency;
          }
          boolean some() {
            return b.value();
          }
        }
        @Configuration
        class B {
          boolean value() { return true; }
        }

    }

使用@SpyBean測試Real方法:

@RunWith(SpringRunner.class)
@SpringBootTest(classes={MyTest.class,MyTest.B.class,MyTest.A.class})
public class MyTest {

     @SpyBean A a;

     @Test
     public  void  myTest() {

       assertTrue(a.some());

    }
    @Component
    class A {
      private B b;
      A(B dependency) {
        this.b = dependency;
      }
      boolean some() {
        return b.value();
      }
    }
    @Configuration
    class B {


      boolean value() { return true; }
    }

}

監視A並嘲笑B如下所示:

@RunWith(SpringRunner.class)
@SpringBootTest(classes={MyTest.class,MyTest.B.class,MyTest.A.class})
public class MyTest {

     @SpyBean A a;

     @MockBean B b;

     @Test
     public  void  myTest() {

         when(b.value()).thenReturn(false);
       assertTrue(a.some());

    }
    @Component
    class A {
      private B b;
      A(B dependency) {
        this.b = dependency;
      }
      boolean some() {
        return b.value();
      }
    }
    @Configuration
    class B {


      boolean value() { return true; }
    }

}

結果 :斷言失敗,因為B的模擬行為為假。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM