いくつかの Spring MVC コントローラーの JUnit テストを作成します。JUnit テストの初期化は、すべてのコントローラー テストに共通しているため、この初期化を行う抽象クラスを作成したいと考えました。
したがって、次のコードを作成しました。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:spring/applicationContext-test.xml", "classpath*:spring/spring-mvc-test.xml" })
@Transactional
public abstract class AbstractSpringMVCControllerTest<T> {
@Autowired
protected ApplicationContext applicationContext;
protected MockHttpServletRequest request;
protected MockHttpServletResponse response;
protected HandlerAdapter handlerAdapter;
protected T controller;
@SuppressWarnings("unchecked")
@Before
public void initContext() throws SecurityException, NoSuchFieldException {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
handlerAdapter = applicationContext.getBean(AnnotationMethodHandlerAdapter.class);
// Does not work, the problem is here...
controller = applicationContext.getBean(T);
}
}
アイデアは、テストしたいコントローラごとに、 my を拡張する JUnit テスト クラスを作成することですAbstractSpringMVCControllerTest
。extends
宣言で指定された型はControllerのクラスです。
たとえば、自分の をテストしたい場合は、次のようなクラスAccountController
を作成します。AccountControllerTest
public class AccountControllerTest extends AbstractSpringMVCControllerTest<AccountController> {
@Test
public void list_accounts() throws Exception {
request.setRequestURI("/account/list.html");
ModelAndView mav = handlerAdapter.handle(request, response, controller);
...
}
}
initContext()
私の問題は、抽象クラスのメソッドの最後の行にあります。この抽象クラスはcontroller
オブジェクトをオブジェクトとして宣言しますT
が、どのようにして Spring Application Context にタイプ の Bean を返すように指示できますT
か?
私はそのようなことを試しました:
Class<?> controllerClass = this.getClass().getSuperclass().getDeclaredField("controller").getType();
controller = (T) applicationContext.getBean(controllerClass);
ではなく、クラスをcontrollerClass
返します。java.lang.Object.class
AccountController.class
もちろん、public abstract Class<?> getControllerClass();
各 JUnit コントローラー テスト クラスによってオーバーライドされるメソッドを作成することはできますが、この解決策は避けたいと思います。
それで、何か考えはありますか?