2

一直在努力解决服务依赖于会话范围内的 bean 失败的测试用例;

产生@SessionScoped User 的类:

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 失败,会话中的用户为 null。

WELD-000052 Cannot return null from a non-dependent producer method:  [method] @Produces @LoggedIn @SessionScoped public org.arg.service.LoginService.getLoggedIn()

谢谢

4

0 回答 0