I had mocked HazelcastInstance and its IMap. I had to test several methods (add, remove) which are having this IMap object is locked, updated, unlocked in the order. But the mocked IMap object is showing zero invocation when I try to run the test. Test class is as follows:
#RunWith(PowerMockRunner.class)
public class Test {
#Mock
private HazelcastInstance hazelcastInstance;
#Mock
private IMap<Object, Object> imap; // but in actual class instead of Object (K, V)
// we are having Class Names. private IMap<ClassA,ClassB> imap;
private TestClass testClass;
#Mock
private ClassA a;
#Mock
private ClassB b;
#Test
public void testAdd() {
when(hazelcastInstance.getMap(anyString())).thenReturn(imap);
testClass.add(a, b);
verify(imap, times(1)).lock(any()); //supposed to be invoked (1 time). But it is showing as zero interaction
verify(imap, times(1)).unlock(any());
}
}
Class to be tested is as follows
public class TestClass {
private IMap<ClassA, ClassB> imap = Hazelcast.newHazelcastInstance().getMap("constant");
public void add(final ClassA key, final ClassB value) {
if (key == null) {
return;
}
try {
imap.lock(key);
imap.put(key, value, 3L, TimeUnit.SECONDS);
} finally {
imap.unlock(key);
}
}
}
In your case, there are two instances of IMAP. The first one is a mock and the second one is a real imap returned by Hazelcast.newHazelcastInstance(). The problem is that the TestClass.add() method uses the real imap, and the verification uses a mock. So it gets a zero of interactions. You need to inject your mock into a TestClass instance using a constructor or a setter.
Sample code of the test
#RunWith(PowerMockRunner.class)
public class Test1 {
#InjectMocks
private TestClass testClass;
#Mock
private IMap<String, Long> imap;
#Test
public void testAdd() {
String key = "a key";
Long value = 123L;
testClass.add(key, value);
verify(imap, times(1)).lock(key);
verify(imap, times(1)).put(eq(key), eq(value), anyLong(), any(TimeUnit.class));
verify(imap, times(1)).unlock(key);
}
}
TestClass after refactoring:
class TestClass {
private IMap<String, Long> imap;
public TestClass(IMap<String, Long> imap) {
this.imap = imap;
}
public void add(final String key, final Long value) {
if (key == null) {
return;
}
try {
imap.lock(key);
imap.put(key, value, 3L, TimeUnit.SECONDS);
} finally {
imap.unlock(key);
}
}
}
The problem is that you mock
#Mock
private HazelcastInstance hazelcastInstance;
When tested class call
Hazelcast.newHazelcastInstance()
That show of architecture problems in tested class. The best way to inject a map into TestClass - pass in constructor arguments.
public class TestClass {
private final IMap<ClassA, ClassB> imap;
public TestClass(IMap<ClassA, ClassB> imap) {
this.imap = imap;
}
Now you can create instance of TestClass
IMap imap = mock(IMap.class)
testClass = new TestClass(imap)
create own imap test class and implements method like this
public class HazelcastMap implements IMap
{
private Map map = new HashMap();
#Override
public void putAll(Map m) {
}
#Override
public int size() {
return 0;
}
#Override
public boolean isEmpty() {
return false;
}
#Override
public boolean containsKey(Object key) {
return map.containsKey(key);
}
#Override
public boolean containsValue(Object value) {
return false;
}
#Override
public Object get(Object key) {
return map.get(key);
}
#Override
public Object put(Object key, Object value) {
map.put(key, value);
return value;
}
#Override
public Object remove(Object key) {
return null;
}
#Override
public boolean remove(Object key, Object value) {
return false;
}
#Override
public void removeAll(Predicate predicate) {
}
#Override
public void delete(Object key) {
}
#Override
public void flush() {
}
#Override
public Map getAll(Set keys) {
return map;
}
#Override
public void loadAll(boolean replaceExistingValues) {
}
#Override
public void loadAll(Set keys, boolean replaceExistingValues) {
}
#Override
public void clear() {
}
#Override
public ICompletableFuture getAsync(Object key) {
return null;
}
#Override
public ICompletableFuture putAsync(Object key, Object value) {
return null;
}
#Override
public ICompletableFuture putAsync(Object key, Object value, long ttl, TimeUnit ttlUnit) {
return null;
}
#Override
public ICompletableFuture putAsync(Object key, Object value, long ttl, TimeUnit ttlUnit, long maxIdle,
TimeUnit maxIdleUnit) {
return null;
}
#Override
public ICompletableFuture setAsync(Object key, Object value) {
return null;
}
#Override
public ICompletableFuture setAsync(Object key, Object value, long ttl, TimeUnit ttlUnit) {
return null;
}
#Override
public ICompletableFuture setAsync(Object key, Object value, long ttl, TimeUnit ttlUnit, long maxIdle,
TimeUnit maxIdleUnit) {
return null;
}
#Override
public ICompletableFuture removeAsync(Object key) {
return null;
}
#Override
public boolean tryRemove(Object key, long timeout, TimeUnit timeunit) {
return false;
}
#Override
public boolean tryPut(Object key, Object value, long timeout, TimeUnit timeunit) {
return false;
}
#Override
public Object put(Object key, Object value, long ttl, TimeUnit ttlUnit) {
return null;
}
#Override
public Object put(Object key, Object value, long ttl, TimeUnit ttlUnit, long maxIdle, TimeUnit maxIdleUnit) {
return null;
}
#Override
public void putTransient(Object key, Object value, long ttl, TimeUnit ttlUnit) {
}
#Override
public void putTransient(Object key, Object value, long ttl, TimeUnit ttlUnit, long maxIdle, TimeUnit maxIdleUnit) {
}
#Override
public Object putIfAbsent(Object key, Object value) {
return null;
}
#Override
public Object putIfAbsent(Object key, Object value, long ttl, TimeUnit ttlUnit) {
return null;
}
#Override
public Object putIfAbsent(Object key, Object value, long ttl, TimeUnit ttlUnit, long maxIdle,
TimeUnit maxIdleUnit) {
return null;
}
#Override
public boolean replace(Object key, Object oldValue, Object newValue) {
return false;
}
#Override
public Object replace(Object key, Object value) {
return null;
}
#Override
public void set(Object key, Object value) {
}
#Override
public void set(Object key, Object value, long ttl, TimeUnit ttlUnit) {
}
#Override
public void set(Object key, Object value, long ttl, TimeUnit ttlUnit, long maxIdle, TimeUnit maxIdleUnit) {
}
#Override
public void lock(Object key) {
}
#Override
public void lock(Object key, long leaseTime, TimeUnit timeUnit) {
}
#Override
public boolean isLocked(Object key) {
return false;
}
#Override
public boolean tryLock(Object key) {
return false;
}
#Override
public boolean tryLock(Object key, long time, TimeUnit timeunit) throws InterruptedException {
return false;
}
#Override
public boolean tryLock(Object key, long time, TimeUnit timeunit, long leaseTime, TimeUnit leaseTimeunit)
throws InterruptedException {
return false;
}
#Override
public void unlock(Object key) {
}
#Override
public void forceUnlock(Object key) {
}
#Override
public String addLocalEntryListener(MapListener listener) {
return null;
}
#Override
public String addLocalEntryListener(EntryListener listener) {
return null;
}
#Override
public String addLocalEntryListener(MapListener listener, Predicate predicate, boolean includeValue) {
return null;
}
#Override
public String addLocalEntryListener(EntryListener listener, Predicate predicate, boolean includeValue) {
return null;
}
#Override
public String addLocalEntryListener(MapListener listener, Predicate predicate, Object key, boolean includeValue) {
return null;
}
#Override
public String addLocalEntryListener(EntryListener listener, Predicate predicate, Object key, boolean includeValue) {
return null;
}
#Override
public String addInterceptor(MapInterceptor interceptor) {
return null;
}
#Override
public void removeInterceptor(String id) {
}
#Override
public String addEntryListener(MapListener listener, boolean includeValue) {
return null;
}
#Override
public String addEntryListener(EntryListener listener, boolean includeValue) {
return null;
}
#Override
public boolean removeEntryListener(String id) {
return false;
}
#Override
public String addPartitionLostListener(MapPartitionLostListener listener) {
return null;
}
#Override
public boolean removePartitionLostListener(String id) {
return false;
}
#Override
public String addEntryListener(MapListener listener, Object key, boolean includeValue) {
return null;
}
#Override
public String addEntryListener(EntryListener listener, Object key, boolean includeValue) {
return null;
}
#Override
public String addEntryListener(MapListener listener, Predicate predicate, boolean includeValue) {
return null;
}
#Override
public String addEntryListener(EntryListener listener, Predicate predicate, boolean includeValue) {
return null;
}
#Override
public String addEntryListener(MapListener listener, Predicate predicate, Object key, boolean includeValue) {
return null;
}
#Override
public String addEntryListener(EntryListener listener, Predicate predicate, Object key, boolean includeValue) {
return null;
}
#Override
public EntryView getEntryView(Object key) {
return null;
}
#Override
public boolean evict(Object key) {
return false;
}
#Override
public void evictAll() {
}
#Override
public Set keySet() {
return null;
}
#Override
public Collection values() {
return null;
}
#Override
public Set entrySet() {
return null;
}
#Override
public Set keySet(Predicate predicate) {
return null;
}
#Override
public Set entrySet(Predicate predicate) {
return null;
}
#Override
public Collection values(Predicate predicate) {
return null;
}
#Override
public Set localKeySet() {
return null;
}
#Override
public Set localKeySet(Predicate predicate) {
return null;
}
#Override
public void addIndex(String attribute, boolean ordered) {
}
#Override
public LocalMapStats getLocalMapStats() {
return null;
}
#Override
public Object executeOnKey(Object key, EntryProcessor entryProcessor) {
return null;
}
#Override
public Map executeOnKeys(Set keys, EntryProcessor entryProcessor) {
return null;
}
#Override
public void submitToKey(Object key, EntryProcessor entryProcessor, ExecutionCallback callback) {
}
#Override
public ICompletableFuture submitToKey(Object key, EntryProcessor entryProcessor) {
return null;
}
#Override
public Map executeOnEntries(EntryProcessor entryProcessor) {
return null;
}
#Override
public Map executeOnEntries(EntryProcessor entryProcessor, Predicate predicate) {
return null;
}
#Override
public QueryCache getQueryCache(String name) {
return null;
}
#Override
public QueryCache getQueryCache(String name, Predicate predicate, boolean includeValue) {
return null;
}
#Override
public QueryCache getQueryCache(String name, MapListener listener, Predicate predicate, boolean includeValue) {
return null;
}
#Override
public boolean setTtl(Object key, long ttl, TimeUnit timeunit) {
return false;
}
#Override
public Object aggregate(Supplier supplier, Aggregation aggregation, JobTracker jobTracker) {
return null;
}
#Override
public Object aggregate(Supplier supplier, Aggregation aggregation) {
return null;
}
#Override
public Collection project(Projection projection, Predicate predicate) {
return null;
}
#Override
public Collection project(Projection projection) {
return null;
}
#Override
public Object aggregate(Aggregator aggregator, Predicate predicate) {
return null;
}
#Override
public Object aggregate(Aggregator aggregator) {
return null;
}
#Override
public String getPartitionKey() {
return null;
}
#Override
public String getName() {
return null;
}
#Override
public String getServiceName() {
return null;
}
#Override
public void destroy() {
}
}
i'm populating my tableview from mysql database but only the column ID is the only one that's populated.
my main:
public void populate() throws Exception{
ObservableList<userdata1> data = FXCollections.observableArrayList();
tableView();
try{
String query = "select * from members";
ps = new Connect().connectDatabase1();
rs = ps.executeQuery(query);
while(rs.next()){
data.add(new userdata1(rs.getInt(1),rs.getString(2),rs.getInt(3)));
tblView.setItems(data);
}
}catch(Exception e){
System.out.print("asdqweasd");
}
}
public void tableView()throws Exception{
tblView.getItems().clear();
tblView.getColumns().clear();
rs = ps.executeQuery("SELECT * FROM members");
ObservableList<userdata1> data = FXCollections.observableArrayList();
TableColumn column1 = new TableColumn("ID");
column1.setMinWidth(85);
column1.setCellValueFactory(new javafx.scene.control.cell.PropertyValueFactory<>("ID"));
TableColumn column2 = new TableColumn("Name");
column2.setMinWidth(565);
column2.setCellValueFactory(new javafx.scene.control.cell.PropertyValueFactory<>("comp_name"));
TableColumn column3 = new TableColumn("STATUS");
column3.setMinWidth(123);
column3.setCellValueFactory(new javafx.scene.control.cell.PropertyValueFactory<>("mem_status"));
tblView.getColumns().addAll(column1,column2,column3);
}
my userdata1:
public class userdata1 {
public SimpleIntegerProperty ID;
public SimpleStringProperty comp_name;
public SimpleIntegerProperty mem_status;
public userdata1(Integer id, String comp_name, Integer mem_status){
this.ID = new SimpleIntegerProperty(id);
this.comp_name = new SimpleStringProperty(comp_name);
this.mem_status = new SimpleIntegerProperty(mem_status);
}
public Integer getID() {
return ID.get();
}
public String getcomp_name(){
return comp_name.get();
}
public Integer getmem_status() {
return mem_status.get();
}
public void setID(Integer id) {
this.ID.set(id);
}
public void setcomp_name(String comp_name ) {
this.comp_name.set(comp_name);
}
public void setmem_status(Integer mem_status) {
this.mem_status.set(mem_status);
}
}
the data mem_status and comp_name is not populating their respective columns
As UserData1 already contains Properties, you can set the according Property to the cellValueFactory:
public class UserData1 {
private StringProperty comp_name;
//additional fields, getters and setters
public StringProperty comp_nameProperty() {
return comp_name;
}
}
setCellValueFactory(cellData -> cellData.getValue().comp_nameProperty());
If you want to stick to the PropertyValueFactory you have to access the fields according to the CamelCase convention:
column2.setCellValueFactory(new PropertyValueFactory<>("comp_name"));
public class UserData1 {
//...
public String getComp_name(){
return comp_name.get();
}
}
I have a bean which contains a lot Boolean fields. I only want to add those fields with true values to json to save some payload. This is a feature and should be based on client's demand so it has to be done in a dynamic way. I don't think annotations will work because they are static things. Any idea on this?
In addition to the Jackson's views you can write a custom Jackson filter which would filter out the negative values of all the boolean fields.
Here is an example:
public class JacksonFilterBoolean {
#JsonFilter("boolean-filter")
public static class Test {
public final Boolean f1;
public final boolean f2;
public final boolean f3;
public final Boolean fNull = null;
public final String f4 = "string";
public Test(Boolean f1, boolean f2, boolean f3) {
this.f1 = f1;
this.f2 = f2;
this.f3 = f3;
}
}
public static class BooleanPropertyFilter extends SimpleBeanPropertyFilter {
#Override
protected boolean include(BeanPropertyWriter writer) {
return true;
}
#Override
protected boolean include(PropertyWriter writer) {
return true;
}
#Override
public void serializeAsField(Object pojo, JsonGenerator jgen,
SerializerProvider provider, PropertyWriter writer)
throws Exception {
if (writer instanceof BeanPropertyWriter) {
BeanPropertyWriter bWriter = (BeanPropertyWriter) writer;
Class<?> type = bWriter.getType().getRawClass();
if (type == Boolean.class || type == boolean.class) {
Object o = bWriter.get(pojo);
if (o != null && !(boolean) o) {
return;
}
}
}
super.serializeAsField(pojo, jgen, provider, writer);
}
}
public static void main(String[] args) throws JsonProcessingException {
Test t = new Test(true, false, true);
ObjectMapper mapper = new ObjectMapper();
mapper.setFilters(new SimpleFilterProvider().addFilter("boolean-filter",
new BooleanPropertyFilter()));
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(t));
}
}
Output:
{
"f1" : true,
"f3" : true,
"fNull" : null,
"f4" : "string"
}
Something like Jackson's JSON Views?
There's an issue open for that in Spring's issue tracker.
Can I have more than one method with #Parameters in junit test class which is running with Parameterized class ?
#RunWith(value = Parameterized.class)
public class JunitTest6 {
private String str;
public JunitTest6(String region, String coverageKind,
String majorClass, Integer vehicleAge, BigDecimal factor) {
this.str = region;
}
#Parameters
public static Collection<Object[]> data1() {
Object[][] data = {{some data}}
return Arrays.asList(data);
}
#Test
public void pushTest() {
System.out.println("Parameterized str is : " + str);
str = null;
}
#Parameters
public static Collection<Object[]> data() {
Object[][] data = {{some other data}}
return Arrays.asList(data);
}
#Test
public void pullTest() {
System.out.println("Parameterized new str is : " + str);
str = null;
}
}
You can use the Theories runner (search for the word theories at that link) to pass different parameters to different methods.
Probably the data1 method, but no guarantee of that, it'll use whichever one the JVM gives junit4 first.
Here's the relevant code from junit:
private FrameworkMethod getParametersMethod(TestClass testClass) throws Exception {
List<FrameworkMethod> methods= testClass.getAnnotatedMethods(Parameters.class);
for (FrameworkMethod each : methods) {
int modifiers= each.getMethod().getModifiers();
if (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))
return each;
}
throw new Exception("No public static parameters method on class " + testClass.getName());
}
So the first public, static annotated method that it finds will be used, but it may find them in any order.
Why do you have uour test written that way? You should only have one #Parameters-annotated method.
It's not designated to have more than one data method. You can see it in skaffman's answer.
Why it's not provided to implement two data methods?
The answer could be: Coupling.
Is it too complex to split this test up into two testcases? You would be able to introduce a small inheritance and share common methods. With two testcases you could provide two separated data methods and test your stuff very well.
I hope it helps.
You can create inner classes for each set of methods that operate on the same parameters. For example:
public class JunitTest6 {
#RunWith(value = Parameterized.class)
public static class PushTest{
private String str;
public PushTest(String region) {
this.str = region;
}
#Parameters
public static Collection<Object[]> data() {
Object[][] data = {{some data}}
return Arrays.asList(data);
}
#Test
public void pushTest() {
System.out.println("Parameterized str is : " + str);
str = null;
}
}
#RunWith(value = Parameterized.class)
public static class PullTest{
private String str;
public PullTest(String region) {
this.str = region;
}
#Parameters
public static Collection<Object[]> data() {
Object[][] data = {{some other data}}
return Arrays.asList(data);
}
#Test
public void pullTest() {
System.out.println("Parameterized new str is : " + str);
str = null;
}
}
}