2012-04-26 91 views
1

我寫了一個泛型類來幫助我們編寫單元測試更容易。它基本上允許我們使用相同的方法來獲得我們的測試設置,並且有一些常用的測試方法。我知道泛型類的關鍵在於不關心我們正在使用的是哪個類,但擁有這些信息是有幫助的(具體實現可以具有適當類型的實例變量)。從Java類型一般要

這裏是我的類:

public abstract class AbstractModuleTest<M extends Module> { 
    @Autowired protected WebDriver driver; 
    private final Type type; 

protected AbstractModuleTest() { 
    final ParameterizedType parameterizedType = 
     (ParameterizedType) getClass().getGenericSuperclass(); 
    type = parameterizedType.getActualTypeArguments()[0]; 
} 

protected <S extends AbstractPage> M setup(final S s, final String errorMsg) { 
    for (final Module m : s.getModules()) { 
    if (m.getClass().equals(type)) { 
     try { 
     final Class c = Class.forName(StringUtils.subStringAfter(type.toString(), " ")); 
     return (M) c.cast(m); 
     } catch (ClassNotFoundException cnfe) { throw new RuntimeException(cnfe); } 
    } 
    } 
    Assert.fail(errorMsg); 
} 

是否有更簡單的方式來獲得我處理類(避免StringUtils.substringAfter調用)?

回答

3

你不需要在方法Class。當m.getClass().equals(type))回報true它的安全做選中投(或許可以有一些角落情況下,如果M是通用的,但您的代碼不抓住他們太):

protected <S extends AbstractPage> M setup(final S s, final String errorMsg) { 
    for (final Module m : s.getModules()) { 
     if (m.getClass().equals(type)) { 
      @SuppressWarnings("unchecked") 
      M result = (M) m; 
      return result; 
     } 
    } 
    Assert.fail(errorMsg); 
} 
+0

呃,我知道我需要更多的咖啡...... – Scott 2012-04-26 17:11:44

1

類名不能包含空格,那麼你可以使用split方法來避免使用StringUtils。

type.toString().split(" ")[1];