2011-04-04 112 views
0

測試:模擬@ org.jboss.seam.annotations.in行爲單元測試

public class BeanTest { 

    private SomeBean target; 

    @Test(groups = "integration") 
    public void checkIfAuthenticationWorks() { 

     ApplicationBean applicationBean = mock(ApplicationBean.class); 
     target = new SomeBean(); 

     // Some cool code to inject applicationBean to target class 

     assertEquals("token", target.authenticate(USERNAME, PASSWORD)); 
    } 
} 

類:

@AutoCreate 
@Name("someBean") 
@Scope(ScopeType.SESSION) 
public class someBean implements Serializable { 

    @Logger 
    private static Log log; 

    @In 
    ApplicationBean applicationBean; 

    public String authenticate(String username, String password) { 

    // Very cool code! 

    return "token"; 
    } 
} 

是否有解決ApplicationBean中注入部分的一些聰明的辦法嗎?

//雅各布

回答

1

首先,使測試Seam的方式,即延長SeamTest

public class BeanTest extends SeamTest { 

    private SomeBean target; 

    @Test(groups = "integration") 
    public void checkIfAuthenticationWorks() { 

     target = (SomeBean) Component.getInstance(SomeBean.class); 
     // target get injected with the MockApplicationBean 


     assertEquals("token", target.authenticate(USERNAME, PASSWORD)); 
    } 
} 

然後,創建一個MockApplicationBeanMOCK優先級,並把它在測試類路徑,以便它將在地方被注入真正的ApplicationBean的:

@Name("applicationBean") 
@Install(precedence = MOCK) 
public class MockApplicationBean extends ApplicationBean 
{ 
    // your mocked ApplicationBean 

} 

最後,注意target必須實例化爲Seam組件,而不是「新」:

SomeBean target = (SomeBean) Component.getInstance(SomeBean.class);