私のコントローラのテストを作成しようとしています。 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();
}
}
}
ありがとうのようなもののためにHamcrestを使用して、私は '@ MockBean'で前にサービスを模擬しようとしていたことに注意してください。私はサービスに実際の呼び出しを模擬するために 'Mockito 'を使用していませんでした。私の最終的なメソッドとあなたが提供したものの唯一の違いは、私のparamsとペイロードはカスタムクラスオブジェクトであり、私は最後の行を使いません: '.andExpect(jsonPath(" $ "、is(equalTo(" Hello、World " ))); '私は終点がアクセス可能であることを示す必要があるからです。 –
コントローラーが返す値を調べる方法を示すために、これらを追加しました。お力になれて、嬉しいです! – SaxyPandaBear