2017-08-05 53 views
0

我想模擬一個對象及其自動裝配的構造函數依賴項之一。如何模擬spring bean及其autowired ctor參數?

例如爲:

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; } 
} 

,這將拋出一個NPE時a::some被稱爲MyTest::myTest。 我該如何嘲笑嘲笑依賴關係?

回答

1

首先,你要選擇的亞軍,

SpringRunner或的Mockito亞軍

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

然後創建了一個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測試實方法:對甲

@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; } 
    } 

} 

間諜和嘲笑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的嘲笑行爲是錯誤的。

+0

對不起,我在添加失蹤的時候再打電話。我想打電話給A,然後委託給B的真正方法。我也想模擬B. B是一些配置。 – mrt181

+0

如果你想調用實際的方法,然後使用@SpyBean。我已經更新了我的答案。 – Barath