コントローラのテストでBeanの作成に関する質問があります。例えば、@Service
注釈及びMainApplicationConfiguration.class
であると注釈されているような試験@Mockアノテーションの感覚は何ですか?
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {MainApplicationConfiguration.class, JPAConfig.class})
@WebAppConfiguration
public class TestMainController {
private MockMvc mockMvc;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(mainController).build();
}
@InjectMocks
private MainController mainController;
@Mock
private EntryService entryService;
@Autowired
DBEntryRepository repository;
@Test
public void testEntryGet() throws Exception {
List<DBEntry> response_data = new ArrayList<>();
response_data.add(new DBEntry(1, 1, "STR", "DATE"));
Mockito.when(entryService.findAllEntries())
.thenReturn(response_data);
MvcResult result = mockMvc.perform(get("/VT/entry/"))
.andExpect(status().isOk()).andReturn();
verify(entryService, times(1)).findAllEntries();
verifyNoMoreInteractions(entryService);
}
}
と
/VT /エントリにマッピングされた制御方式/
@RequestMapping(value = "/entry/", method = RequestMethod.POST)
public ResponseEntity<Void> createEntry(@RequestBody DBEntry entry, UriComponentsBuilder ucBuilder) {
System.out.println("Creating entry " + entry.getNum());
try {
entryService.saveEntry(entry);
entryService.refreshEntryService();
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<Void>(HttpStatus.BAD_REQUEST);
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/entry/{id}").buildAndExpand(entry.getId()).toUri());
return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}
EntryService
あります@EnableWebMvc
の設定とこのプロジェクトのスキャンはEntryService
です。
私は、このコントローラが実際にこのアプリケーションを実際のアプリケーションで使用し、すべてがMainApplicationConfiguration.class
で結合されていることを示したいと思います。
質問:entryService
と@Mock
の注釈が私のテスト実行の範囲内の私のコントローラコードで終わったのはなぜですか?そのインスタンスのためだけでなく、コントローラの内部で別のBean(EntryService)をインスタンス化する必要があります。なぜこの注釈が(そのスコープ内の)そのBeanのすべての出現を嘲笑したのですか?私は考えていました、私はMainApplicationConfiguration.class
の代わりに他の文脈のウェブコンテキスト全体を書き込んで、それを模擬して現在の定義に置き換えてください。なぜこの単純な注釈がそのようなことをしたのか、私は絶対に混乱しています。
誰かがこの魔法を理解できれば、@ InjectMockと@Mockの違いは何ですか?
ご注意いただきありがとうございます!私の質問がかなりばかげている場合は申し訳ありません。私は非常に新しい、それは動作しますが、私はまだ魔法を持っていません。 @InjectMocks
ためdocumentationで
これは質問の主要部分の回答ではありません。 – Alex
@Alex私のコメントには違いがあります。あなたはこの[post](https://stackoverflow.com/questions/16467685/difference-between-mock-and-injectmocks)でもっと見ることができます。 –
あなたは何かを引用しようとしますが、この引用はこの質問に関する答えではありません(あなたの努力に感謝します) My EntryServiceに@Mock注釈が付いています – Alex