簡體   English   中英

在基於Mockito的junit測試類中注入嵌套的依賴項

[英]Inject nested dependencies in mockito based junit test class

我正在為一個控制器編寫單元測試,這是我的代碼

public class MyController
{
    @Inject
    private MyService myService;

    public List<Car> getCars()
    {
        myService.getCars();
    }
}

public class MyServiceImpl implements MyService 
{
    @Inject
    AService aService;

    @Inject
    BService bService;

    public List<Car> getCars()
    {
        aService.getCars();
    }
}


Public class MyControllerTest
{

    private MockMvc standAloneMockMvc;

    @InjectMocks
    MyController myController;

    @Mock
    private MyService myService;

    @Before
    public void initTestObjs() 
    {
        MockitoAnnotations.initMocks(this);

        this.standAloneMockMvc = MockMvcBuilders.standaloneSetup(myController).build();

    }

    @Test
    public void testGetAllCars() throws Exception
    {
        String url = "/car/list";

        List<Car> listCars = new ArrayList<Car>();
        Car car = new Car();
        listCars.add(car);

        Mockito.when(myService.getCars()).thenReturn(listCars);

        MvcResult result = standAloneMockMvc.perform(MockMvcRequestBuilders.get(url))
        .andDo(MockMvcResultHandlers.print())
        .andExpect(MockMvcResultMatchers.status().isOk())
        .andReturn();

        String jsonResult = result.getResponse().getContentAsString();
    }
}

當嘗試加載aService和bService時,在MyControllerTest中為myService創建bean時遇到錯誤。

有人可以幫忙嗎? 還有其他人遇到類似的問題嗎?

堆棧跟蹤:

Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.xyz.AService com.xyz.aService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.xyz.AService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.inject.Inject()}  
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:571)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)

您需要完全提供所有模擬實現,即。 您的測試類無法弄清楚這些AService和aService是什么; BService bService; 是。

@mock將查找要顯示的所有字段(模擬)

因此,您可以為他們提供模擬提供模擬執行

..

private MockMvc standAloneMockMvc;

    @InjectMocks
    MyController myController;

    @Mock
    private MyService myService;

    @Mock
    AService aService;

    @Mock
    BService bService;

....

暫無
暫無

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

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