私はコントローラの注入口注入によってフィールド注入を交換しようとしていますが、それはベストプラクティスのようです。 アプリケーションを実行すると、両方のソリューションで動作します。フィールド注入検査VSコンストラクタ注入
私の問題は、私のコントローラのユニットテストです。 フィールド注入を使用するコントローラのテストクラスを記述します。 正常に動作します。 私はフィールド注入をコンストラクタ注入に置き換えました。テストは失敗します。ここで
は(フィールド注射で)私の最初のコントローラーです:
今@Controller
public class DashboardController {
@Autowired
private MyService myService;
@RequestMapping("/")
public String index(Model model) {
MyPojo myPojo = myService.getMyPojo();
model.addAttribute("myPojo", myPojo);
return "dashboard";
}
}
(constuctor注射で)新しいコントローラ:
@Controller
public class DashboardController {
private final MyService myService;
@Autowired
public DashboardController(MyService myService) {
this.myService = myService;
}
@RequestMapping("/")
public String index(Model model) {
MyPojo myPojo = myService.getMyPojo();
model.addAttribute("myPojo", myPojo);
return "dashboard";
}
}
とテストクラス:
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {MyApplication.class})
@WebAppConfiguration
@TestPropertySource(locations = "classpath:/application.properties")
public class DashboardControllerUnitTests {
@InjectMocks
private DashboardController dashboardController;
@Mock
private MyService myService;
private MockMvc mockMvc;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders
.standaloneSetup(dashboardController)
.build();
}
@Test
public void getDashboard() throws Exception {
doReturn(new MyPojo()).when(myService).getMyPojo();
mockMvc.perform(get("/"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(model().attribute("myPojo", equalTo(new MyPojo()))); // The test fail here
verify(myService).getMyPojo();
}
}
私のコントローラの初期バージョンでテストを実行すると、正常に動作します。 新しいバージョンのコントローラ(コンストラクタインジェクション付き)で同じテストを実行すると、myPojoはnullになり、テストは失敗します。
コンストラクタが注入されていると、mockitoがサービスをモックしないようです。 私に問題がある理由と解決方法を知っていますか?あなたはこのような何かに設定方法を変更する必要が
あなたは '代わりMyService'に' @ MockBean'注釈を使用してみましたか?そして、 'DashboardController'に単純な' @ Autowired'を使用しますか? 'setup()'メソッド全体を削除しますか? –