一直在努力解决一个服务依赖于会话中的会话范围bean失败的测试用例;
生成@SessionScoped用户的类:
public class LoginService {
private User user;
public void login(String name) {
if ("userA".equals(name)) {
user = new User(name, "permissionA");
} else if ("userB".equals(name)) {
user = new User(name, "permissionB");
} else {
user = new User("anonymous", "");
}
}
@Produces
@LoggedIn
@SessionScoped
public User getLoggedIn() {
return this.user;
}
}
使用@LoggedIn用户的服务:
public class MediaService {
@Inject
@LoggedIn
private User user;
public void updateImage(){
if("permissionA".equals(user.getPermission())) {
System.out.println("user can update image");
} else {
System.out.println("user can not update image");
}
}
}
测试:
@RunWith(Arquillian.class)
public class ServiceTest {
@Deployment
public static WebArchive deployment() {
return ShrinkWrap
.create(WebArchive.class, "test.war")
.addClass(LoggedIn.class)
.addClass(LoginService.class)
.addClass(MediaService.class)
.addClass(User.class)
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
}
@Inject
private LoginService lservice;
@Inject
private MediaService mservice;
@Test
public void testLogin() {
lservice.login("userA");
}
@Test
public void testUpdateImage(){
mservice.updateImage();
}
}
使用arquillian远程容器进行测试,第一次测试(testLogin)传递,testUpdateImage失败,并且会话中有空用户。
WELD-000052 Cannot return null from a non-dependent producer method: [method] @Produces @LoggedIn @SessionScoped public org.arg.service.LoginService.getLoggedIn()
由于