2017-07-05 3 views
0

私のコントローラのテストを作成しようとしています。 Webサービスが動作しているときは、すべて正常に動作します。私は、テストを実行したときしかし、私が手に:あなたは以下を参照することができたようSpringを使用した自動配線時のBeanの作成

Error creating bean with name 'Controller': Unsatisfied dependency expressed through field 'service'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.prov.Service' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

が、私はコンポーネントのスキャナが適切に注釈を見つけることができるように正しくAutowiredと私のプロジェクト構造が正しく設定されているすべてのものを持っていると信じて、まだ私はまだこのエラーが発生します。

コントローラー:

@RestController 
@RequestMapping("/api") 
public class Controller { 

    @Autowired 
    private Service service; 

    @JsonView(Views.All.class) 
    @RequestMapping(value = "/prov/users", method = RequestMethod.POST) 
    @ResponseBody 
    public CommonWebResponse<String> handleRequest(@RequestBody UserData userData) { 
     return service.prov(userData); 
    } 
} 

サービス:

@Service 
public class Service { 

    @Autowired 
    private Repo repo; 

    @Autowired 
    private OtherService otherService; 

    public CommonWebResponse<String> prov(UserData userData) { 
     // do stuff here 
     return new SuccessWebResponse<>("Status"); 
    } 
} 

コントローラテスト:

@RunWith(SpringRunner.class) 
@WebMvcTest(
     controllers = Controller.class, 
     excludeFilters = { 
       @ComponentScan.Filter(
         type = FilterType.ASSIGNABLE_TYPE, 
         value = {CorsFilter.class, AuthenticationFilter.class} 
       ) 
     } 
) 
@AutoConfigureMockMvc(secure = false) 
public class ControllerTest { 

    public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); 

    @Autowired 
    private MockMvc mvc; 

    @Test 
    public void connectToEndpoint_shouldReturnTrue() { 
     UserData userData = new UserData("a", "bunch", "of", "fields"); 
     try { 
      mvc.perform(post("/api/prov/users").contentType(APPLICATION_JSON_UTF8) 
        .content(asJsonString(userData)) 
        .accept(MediaType.ALL)) 
        .andExpect(status().isOk()); 
     } catch (Exception e) { 
      Assert.fail(); 
     } 
    } 

} 

答えて

1

Controllerクラスは、あなたのサービスクラスをautowires。したがってControllerはServiceクラスのBeanの作成に依存するため、ControllerクラスのテストにはServiceクラスの存在が必要です。つまり、あなたのサービスクラスを@Autowiredにするか、またはMockitoのようなものを使って(できれば)模擬してください。

(コード例で編集):

@RunWith(SpringRunner.class) 
@WebMvcTest(Controller.class) 
public class ControllerTest { 
    @MockBean 
    private Service service 

    @Autowired 
    private MockMvc mvc; 

    @Test 
    public void foo() { 
     String somePayload = "Hello, World"; 
     String myParams = "foo"; 
     when(service.method(myParams)).thenReturn(somePayload); 
     mvc.perform(get("my/url/to/test").accept(MediaType.APPLICATION_JSON)) 
      .andExpect(status().isOk()) 
      .andExpect(jsonPath("$", is(equalTo("Hello, World")))); 
    } 
} 

この例では、is()equalTo()

+0

ありがとうのようなもののためにHamcrestを使用して、私は '@ MockBean'で前にサービスを模擬しようとしていたことに注意してください。私はサービスに実際の呼び出しを模擬するために 'Mockito 'を使用していませんでした。私の最終的なメソッドとあなたが提供したものの唯一の違いは、私のparamsとペイロードはカスタムクラスオブジェクトであり、私は最後の行を使いません: '.andExpect(jsonPath(" $ "、is(equalTo(" Hello、World " ))); '私は終点がアクセス可能であることを示す必要があるからです。 –

+1

コントローラーが返す値を調べる方法を示すために、これらを追加しました。お力になれて、嬉しいです! – SaxyPandaBear

関連する問題