public class XObject {
...
}
public class XObjectWrapper
{
private final XObject xo;
public XObjectWrapper(XObject xo) {
this.xo = xo;
}
//delegated methods
...
}
I have List<XObject>, I want to get List<XObjectWrapper>.
Obviously, I can do something like this:
List<XObjectWrapper> wrappedList = new ArrayList<XObjectWrapper> ();
for(XObject xo : xoList)
{
wrappedList.add(new XObjectWrapper(xo));
}
Can I use some new java8 feature, and do it with a single line?
This will do:
List<XObjectWrapper> wrappedList =
xoList.stream().map(XObjectWrapper::new).collect(toList());
(Assuming import static java.util.stream.Collectors.toList;)
Update
For completeness, and due to possible errors in your code, here is a self-contained example:
import static java.util.stream.Collectors.toList;
import java.util.ArrayList;
import java.util.List;
static class XObjectWrapper {XObjectWrapper(Object o) {}}
static class XObject {}
public class Test {
public static void main(String[] args) {
List<Object> xoList = new ArrayList<>();
List<XObjectWrapper> wrappedList =
xoList.stream().map(XObjectWrapper::new).collect(toList());
System.out.println(wrappedList);
}
}
Related
While trying to run my test for the following code. I am getting some error detailed below.
I observed at the time it makes mkdirs() calls in my code throws IllegalArgumentException when I try to run my test.
MyClass.java
package com.javaeasily.demos.junit;
import java.util.ArrayList;
public class MyClass {
private final NodeHelper nodeHelper;
private static final ArrayList<String> ACTIVE_SERVICES_POST_RECONFIGURE = new ArrayList<>();
// Only allow construction if number is greater than one
MyClass() {
ACTIVE_SERVICES_POST_RECONFIGURE.add("my-node-" + NodeUtils.getMyNode());
nodeHelper = new NodeHelper();
}
public void reconfigureNode() {
if (ACTIVE_SERVICES_POST_RECONFIGURE.isEmpty()) {
return;
}
try {
nodeHelper.createStagingDir();
} catch (Exception e) {
throw new RuntimeException("Cannot reconfigure node");
}
}
}
NodeUtils.java
package com.javaeasily.demos.junit;
import org.apache.commons.lang3.StringUtils;
public class NodeUtils {
private static final String HOSTNAME_PREFIX = "my-node-";
public static String hostnameToNode(String hostname) {
if (!hostname.startsWith(HOSTNAME_PREFIX)) {
throw new IllegalArgumentException(hostname + " is not recognized hostname");
}
return StringUtils.removeStart(hostname, HOSTNAME_PREFIX);
}
public static String getHostname() {
return System.getenv("HOSTNAME");
}
public static String getMyNode() {
return hostnameToNode(getHostname());
}
}
NodeHelper.java
package com.javaeasily.demos.junit;
import java.io.File;
public class NodeHelper {
private static final String STAGING_DIR = "/staging/";
public void createStagingDir() {
File stagingDir = new File(STAGING_DIR);
if (!stagingDir.exists() && !stagingDir.mkdirs()) {
throw new IllegalArgumentException("Could not create staging dir");
}
}
}
MyClassTest.java
package com.javaeasily.demos.junit;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
#ExtendWith(MockitoExtension.class)
public class MyClassTest {
private MyClass myclass;
#BeforeEach
public void SetUp() {
try (MockedStatic<NodeUtils> nodeUtilsMockedStatic = Mockito.mockStatic(NodeUtils.class);) {
nodeUtilsMockedStatic.when(NodeUtils::getMyNode).thenReturn("foo");
myclass = new MyClass();
}
}
#Test
public void testReconfigureNode() {
myclass.reconfigureNode();
}
}
When I try to run my test I get following error:
java.lang.RuntimeException: Cannot reconfigure node
at com.javaeasily.demos.junit.MyClass.reconfigureNode(MyClass.java:22)
Post debugging I see that:
java.lang.IllegalArgumentException: Could not create staging dir
Does anyone care to enlighten me as to what I am doing wrong?
To mock NodeHelper you should not create it inside MyClass, but inject it from the outside via the constructor. i.e.
MyClass(Nodehelper nodeHelper) {
ACTIVE_SERVICES_POST_RECONFIGURE.add("my-node-" + NodeUtils.getMyNode());
this.nodeHelper = nodeHelper;
}
This allows you to create a mocked NodeHelper in your test, pass it to MyClass and set the desired behavior as expectations.
As I mentioned in the title. Here is my code below
import java.lang.reflect.Field;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ObjectNode;
public class ReflectClass {
public Double getDoubleKey() {
return doubleKey;
}
public void setDoubleKey(Double doubleKey) {
this.doubleKey = doubleKey;
}
public Long getLongKey() {
return longKey;
}
public void setLongKey(Long longKey) {
this.longKey = longKey;
}
private Double doubleKey;
private Long longKey;
public ReflectClass(JsonNode node) throws IllegalAccessException {
Field[] fields = this.getClass().getDeclaredFields();
for (Field field : fields) {
if (field.getType().equals(Double.class)) {
field.setDouble(this, node.get(field.getName()).asDouble());
} else if (field.getType().equals(Long.class)) {
field.setLong(this, node.get(field.getName()).asLong());
}
}
}
public static void main(String[] args) throws IllegalAccessException {
ObjectNode jNode = new ObjectMapper().createObjectNode();
jNode.put("doubleKey", 1.0);
jNode.put("longKey", 11L);
new ReflectClass(jNode);
}
}
However when I run the code above, the error like below pops up.
java.lang.IllegalArgumentException: Can not set java.lang.Double field models.weibo.ReflectClass.doubleKey to (double)1.0
I can certainly initialise the class instance by the traditional way like this.doubleKey = node.get("doubleKey").asDouble(). However if there are too many fields in this class, I'd prefer to initialise it through a loop.
I need to write the method which let to store always last 10 (the newset) elements and only 10.I have tried to use CircularFifoBuffer.It works perfectly usee like this:
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import org.apache.commons.collections4.queue.CircularFifoQueue;
public class Main {
public static void main(String[] args) {
Queue<Integer> fifo = new CircularFifoQueue<Integer>(3);
fifo.add(11);
fifo.add(22);
fifo.add(33);
fifo.add(44);
fifo.add(55);
System.out.println(fifo); // [33, 44, 55]
But it doesn;t work when used inside the method:
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import org.apache.commons.collections4.queue.CircularFifoQueue;
public class TV {
public int channelNumber = 11;
public int getChannelNumber() {
return channelNumber;
}
public void addToChannelsHistory(int channnelNumber) {
Queue<Integer> fifo = new CircularFifoQueue<Integer>(3);
fifo.add(channnelNumber);
System.out.print(fifo);
}
}
Could you help what to use instead?
You have to use the notion of attribute, a member of your class which is a data, not a method:
public class TV {
private final Queue<Integer> fifo = new CircularFifoQueue<Integer>(3);
public Queue<Integer> getChannelNumbers() {
return fifo;
}
public Integer getChannelNumber() {
return fifo.isEmpty() ? null : fifo.peek();
}
public void addToChannelsHistory(int channnelNumber) {
fifo.add(channnelNumber);
}
public String toString() {
return fifo.toString();
}
public static void main( String[] args ) {
TV tv = new TV();
tv.addToChannelsHistory(11);
tv.addToChannelsHistory(22);
tv.addToChannelsHistory(33);
tv.addToChannelsHistory(44);
tv.addToChannelsHistory(55);
System.out.print( tv );
}
}
Forgive me if I've misunderstood, but as far as I can tell by copying this locally, this works. However, in a Java program, the main method is the entry point into the program. If you aren't instantiating your TV class in the main method, the addToChannelHistory method will never get run. For instance, this works for me:
public class TV {
public int channelNumber = 11;
public int getChannelNumber() {
return channelNumber;
}
public void addToChannelsHistory(int channnelNumber) {
Queue<Integer> fifo = new CircularFifoQueue<Integer>(3);
fifo.add(channnelNumber);
System.out.print(fifo);
}
public static void main(String[] args) {
TV tv = new TV();
tv.addToChannelsHistory(11);
tv.addToChannelsHistory(22);
tv.addToChannelsHistory(33);
tv.addToChannelsHistory(44);
tv.addToChannelsHistory(55);
}
}
Running that program should print out 33 to the console.
#Mocked Provider provider;
public static class Provider {
public static List<Integer> getStaticList() {
return new ArrayList<>();
}
public static List<Integer> test() {
return getStaticList();
}
}
#Test
public void testStatic() {
ArrayList<Object> list = new ArrayList<>();
list.add(1);
new Expectations() {
{
Provider.getStaticList();
result = list;
}
};
assertThat(Provider.test(), JUnitMatchers.hasItem(1));
}
I want to mock (with JMockit) one static method that is called within another one. How can I do that? The above test fails. The real Provider.test method is never called.
The code below changes the behaviour of doSomething static method only, without affecting other static methods.
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
#RunWith(PowerMockRunner.class)
#PrepareForTest({Foo.class})
public class Snipets {
#Test
public void hoge() throws Exception {
PowerMockito.spy(Foo.class);
PowerMockito.when(Foo.class, "doSomething").thenReturn("dummy");
String actual = Foo.doSomething();
assertEquals("dummy", actual);
}
}
Foo.java
public class Foo {
public static String doSomething() {
return "foo";
}
}
Source: https://gist.github.com/mid0111/8859159
You can use partial mocking:
#Test
public void testStatic() {
new Expectations(Provider.class) {{ Provider.getStaticList(); result = 1; }};
List<Integer> test = Provider.test();
assertTrue(test.contains(1));
}
(With no "#Mocked Provider" field for the test above.)
I used a very simple method of writing a conditional answer like this:
PowerMockito.mockStatic(<MyMockedClass>.class, invocation -> {
if (invocation.getMethod().getName().equals("<methodToMockName>")) {
return <mockedValue>;
}
return invocation.callRealMethod();
});
Need to setup JMock code to test call back with google protobuf
Full project is located at http://github.com/andrewmilkowski/template-transport
In short, following are methods signatures (below)
what I need to do is to test method getLongValue, using Jmock JUnit4Mockery
what is the best and cleanest way to go about this
thanks much!
package com.argmaps.client.proto;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.fepss.rpc.server.RpcApplication;
import com.fepss.rpc.client.RpcChannelImpl;
import org.apache.tapestry5.ioc.MappedConfiguration;
import com.google.protobuf.RpcController;
import com.google.protobuf.RpcCallback;
import com.argmaps.transport.proto.generated.TransportServer.ProtoService;
import com.argmaps.transport.proto.generated.TransportServer.ProtoService.Stub;
import com.argmaps.transport.proto.generated.TransportServer.DefaultLongValue;
import com.argmaps.transport.proto.generated.TransportServer.LongValue;
import com.argmaps.transport.proto.fepss.ProtoServer.TransportHandler;
public class TransportClient {
protected final Log LOG = LogFactory.getLog(this.getClass().getName());
private RpcController controller;
private TransportHandler transportHandler;
private ProtoService.Interface service;
private void open(String host, int port) {
RpcChannelImpl channel = new RpcChannelImpl(host, port);
controller = channel.newRpcController();
service = ProtoService.newStub(channel);
}
protected static class LongValueRpcCallback implements RpcCallback<LongValue> {
private long longValue = 0L;
#Override
public void run(LongValue result) {
longValue = result.getLongValue();
}
private long getLongValue() {
return longValue;
}
}
private void close() {
}
public long getLongValue(LongValueRpcCallback longValueRpcCallback) {
DefaultLongValue defaultLongValue = DefaultLongValue.newBuilder().setLongValue(0L).build();
service.getLongValue(controller, defaultLongValue, longValueRpcCallback);
if (LOG.isDebugEnabled()) {
LOG.debug("Long value from server:" + longValueRpcCallback.getLongValue());
}
return longValueRpcCallback.getLongValue();
}
public static void main(String[] args) {
String host = "localhost";
int port = 9090;
final String portArgKey = "--port=";
for (String cmd : args) {
if (cmd.startsWith(portArgKey)) {
port = Integer.parseInt(cmd.substring(portArgKey.length()));
break;
}
}
TransportClient c = new TransportClient();
c.open(host, port);
c.getLongValue(new LongValueRpcCallback());
c.close();
}
public TransportClient() {
}
public static class TransportModule {
public static void contributeIoHandler(MappedConfiguration<String, ProtoService> configruation) {
configruation.add(ProtoService.getDescriptor().getFullName(), new TransportHandler());
}
}
}
Because of the callback, needed to:
create abstract class LongValueRpcCallbackTemplate implements RpcCallback
create class LongValueRpcCallback extends LongValueRpcCallbackTemplate
and then complete implementation in the test class
Test class:
package com.argmaps.client.proto;
import com.argmaps.transport.proto.generated.TransportServer;
import com.fepss.rpc.client.RpcChannelImpl;
import com.google.protobuf.RpcController;
import org.jmock.Expectations;
import org.junit.Test;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JUnit4Mockery;
import static org.junit.Assert.assertEquals;
public class TransportClientTest {
Mockery context;
#Before
public void before() {
context = new JUnit4Mockery();
}
private class TestLongValueRpcCallback extends LongValueRpcCallbackTemplate {
private long longValue = 123456789L;
#Override
protected long getLongValue() {
return longValue;
}
}
#Test
public void testGetLongValue() {
final TransportServer.ProtoService.Interface mockedTransportServer = context.mock(TransportServer.ProtoService.Interface.class);
final RpcChannelImpl channel = new RpcChannelImpl("localhost", 9090);
final RpcController controller = channel.newRpcController();
final TransportServer.DefaultLongValue defaultLongValue = TransportServer.DefaultLongValue.newBuilder().setLongValue(0L).build();
com.argmaps.client.proto.TransportClient testObject = new TransportClient(controller, mockedTransportServer);
final TestLongValueRpcCallback testLongValueRpcCallback = new TestLongValueRpcCallback();
final long testLongValue = 123456789L;
context.checking(new Expectations() {
{
one(mockedTransportServer).getLongValue(controller, defaultLongValue, testLongValueRpcCallback);
}
});
assertEquals(testLongValue, testObject.getLongValue(testLongValueRpcCallback));
}
}