Java @Inject不工作 - 方法返回null

时间:2018-05-12 11:19:56

标签: java mockito

不确定界面为什么不被注入。测试始终返回null。我在beans.xml中也有WEB-INF。为什么它返回null?

我还尝试使用@ApplicationScoped和一个产生新TImpl

的类来注释服务类
public interface T {
 int test_method(int n );
 public void addToSession(Session session);
} 

@Handler // Qualifier
public TImpl implements T{

 private static Set<Session> sessions = Collections.synchronizedSet(new HashSet<Session>());
 public TImpl();

 @Override
 int test_method(int n){ return n * 2; }

 @Override
 public void addToSession(Session session){ 
  sessions.add(session);
}
}

public class TService implements Serializable {

 private @Inject @Handler T;

 public TService() {}
 ... 

 int test_method_service(int n) { return T.test_method(n); }
 public void addToSession(Session session) { T.addToSession(session); }

}

public class L extends Endpoint {

 TService service;

 public L(TService s){ this.service = t; }
 public L(){}


 @Override
 public void OnOpen(Session session, ... ) 

 servive.addToSession(session); // null pointer
 ...
}

堆栈跟踪

java.lang.NullPointerException
at com.vio.sockets.configuration.MessageEndPoint.onOpen(MessageEndPoint.java:40)
at org.apache.tomcat.websocket.server.WsHttpUpgradeHandler.init(WsHttpUpgradeHandler.java:133)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:914)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1457)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)

1 个答案:

答案 0 :(得分:0)

您说您的测试返回null,但堆栈跟踪会说明不同的故事:expected:<6> but was:<0>不是NullPointerException,这意味着对service.test_method_service(3)的调用返回0 - 那是零。

这看起来就像是Mockito模拟的预期行为:你有T的模拟注入你的service实例,它在模拟T中调用test_method(),而Mockito的返回int的方法的默认值为0。

当您想要不同的行为时,您必须设置模拟的行为:

Mockito.when(t.test_method(3)).thenReturn(6);