How to import 'org.hamcrest.collection' in junit to test collection methods - assertion

I am using Junit 5 and getting the following error while importing collection packages
The import org.hamcrest.collection cannot be resolved
I need to validate assertThat method & hasSize() from collection for which the below import should be done.
import org.hamcrest.collection.IsEmptyCollection;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
import static org.hamcrest.MatcherAssert.assertThat;
import java.awt.List;
import java.util.ArrayList;
public class PortJUnit {
PortBO portBO;
ArrayList<Port> list = new ArrayList<Port>();
#Before
public void createObjectForPort()
{
portBO = new PortBO();
}
#Test
public void testPortDetails()
{
list.add(new Port(101,"abc","cbe"));
list.add(new Port(102,"abd","chennai"));
list.add(new Port(103,"abe","bangalore"));
list.add(new Port(104,"abf","mumbai"));
list.add(new Port(105,"abg","delhi"));
String detail = "107,abh,Toronto";
portBO.addElementAtSpecfiedPosition(list, 6, detail);
assertThat(list, hasSize(6));
}
}

I suggest that you use hamcrest-core dependency.
Please try to use instead - hamcrest-all-1.3.jar and your problem will be solved.

Related

How can I run my custom gradle task in the unit test?

I need to run my gradle task to test basic functional in the unit test:
import org.gradle.api.Project;
import org.gradle.testfixtures.ProjectBuilder;
import org.junit.Test;
public class IwillfailyouPluginTest {
#Test
public void applyPlugin() {
final Project project = ProjectBuilder.builder().build();
project.getPlugins().apply(IwillfailyouPlugin.class);
project.task("iwillfailyou").// what method should I run?
}
}
But I can not find the method to run it. Help me, please
My understanding is that ProjectBuilder is more for unit-like tests. So with what you have, you should only be asserting that a task named iwillfailyou exists, is of a certain type, and has the correct configuration.
public class IwillfailyouPluginTest {
#Test
public void applyPlugin() {
final Project project = ProjectBuilder.builder().build();
project.getPlugins().apply(IwillfailyouPlugin.class);
assertTrue(project.getTasks().getNames().contains("iwillfailyou"));
MyCustomTaskType iwillfailyou = project.getTasks().getByName("iwillfailyou");
assertEquals(123, iwillfailyou.getSomeConfig())
}
}
It looks looks you're trying to test the behavior/function of the custom task. For that sort of test, you would use TestKit.
import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.io.FileWriter;
import java.nio.file.Files;
import org.gradle.testkit.runner.GradleRunner;
import org.gradle.testkit.runner.BuildResult;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class IwillfailyouPluginFunctionalTest {
#Test
void canRunTask() throws IOException {
// Setup the test build
File projectDir = new File("build/functionalTest");
Files.createDirectories(projectDir.toPath());
writeString(new File(projectDir, "settings.gradle"), "");
writeString(new File(projectDir, "build.gradle"), "plugins {" + " id('i.will.fail.you')" + "}");
// Run the build
GradleRunner runner = GradleRunner.create();
runner.forwardOutput();
runner.withPluginClasspath();
runner.withArguments("iwillfailyou");
runner.withProjectDir(projectDir);
BuildResult result = runner.build();
// Verify the result
Assertions.assertTrue(result.getOutput().contains("someoutput from the iwillfailyou task"));
}
private void writeString(File file, String string) throws IOException {
try (Writer writer = new FileWriter(file)) {
writer.write(string);
}
}
}

Add a unit test for Flink SQL

I am using Flink v1.7.1. When I finished a Flink streaming job with tableSource, SQL and tableSink, I have no idea how to add a unit test for it.
I found a good example about how to testing flink sql with the help of user mailing list, here is a example.
package org.apache.flink.table.runtime.stream.sql;
import org.apache.flink.api.common.typeinfo.BasicTypeInfo;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.api.java.tuple.Tuple5;
import org.apache.flink.api.java.typeutils.RowTypeInfo;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.TableEnvironment;
import org.apache.flink.table.api.java.StreamTableEnvironment;
import org.apache.flink.table.runtime.utils.JavaStreamTestData;
import org.apache.flink.table.runtime.utils.StreamITCase;
import org.apache.flink.test.util.AbstractTestBase;
import org.apache.flink.types.Row;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
/**
* Integration tests for streaming SQL.
*/
public class JavaSqlITCase extends AbstractTestBase {
#Test
public void testRowRegisterRowWithNames() throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
StreamTableEnvironment tableEnv = TableEnvironment.getTableEnvironment(env);
StreamITCase.clear();
List<Row> data = new ArrayList<>();
data.add(Row.of(1, 1L, "Hi"));
data.add(Row.of(2, 2L, "Hello"));
data.add(Row.of(3, 2L, "Hello world"));
TypeInformation<?>[] types = {
BasicTypeInfo.INT_TYPE_INFO,
BasicTypeInfo.LONG_TYPE_INFO,
BasicTypeInfo.STRING_TYPE_INFO};
String[] names = {"a", "b", "c"};
RowTypeInfo typeInfo = new RowTypeInfo(types, names);
DataStream<Row> ds = env.fromCollection(data).returns(typeInfo);
Table in = tableEnv.fromDataStream(ds, "a,b,c");
tableEnv.registerTable("MyTableRow", in);
String sqlQuery = "SELECT a,c FROM MyTableRow";
Table result = tableEnv.sqlQuery(sqlQuery);
DataStream<Row> resultSet = tableEnv.toAppendStream(result, Row.class);
resultSet.addSink(new StreamITCase.StringSink<Row>());
env.execute();
List<String> expected = new ArrayList<>();
expected.add("1,Hi");
expected.add("2,Hello");
expected.add("3,Hello world");
StreamITCase.compareWithList(expected);
}
}
the related code is here

Mockito not injecting repository mocks

I am trying to write tests for spring boot application which has repositories.
My test class looks like this:
package se.volvo.spp.controller.spp;
import com.datastax.driver.core.utils.UUIDs;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.*;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.data.cassandra.repository.MapId;
import org.springframework.data.cassandra.repository.support.BasicMapId;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import se.volvo.spp.BaseTest;
import se.volvo.spp.config.JacksonConfig;
import se.volvo.spp.dao.cassandra.*;
import se.volvo.spp.dto.ServiceAgentDTO;
import se.volvo.spp.exception.NotFoundException;
import se.volvo.spp.repository.AssignmentRepository;
import se.volvo.spp.repository.ServiceAgentRepository;
import se.volvo.spp.service.impl.ServiceAgentService;
import javax.inject.Inject;
import java.util.*;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
public class ServiceAgentControllerTest extends BaseTest {
#Autowired
private MockMvc mockMvc;
#Mock
ServiceProviderDAO serviceProviderDAO;
#Mock
ServiceTypeDAO serviceTypeDAO;
#Mock
ServiceDefinitionDAO serviceDefinitionDAO;
#Mock
ServiceAgentDAO serviceAgentDAO;
#Mock
AssignmentDAO assignmentDAO;
#Mock
ServiceAgentRepository serviceAgentRepository;
#Mock
AssignmentRepository assignmentRepository;
#InjectMocks
ServiceAgentService serviceAgentService;
#Before
public void setUp() {
serviceAgentDAO.setId(UUID.fromString("e5cec1dc-422b-11e8-842f-0ed5f89f718b"));
serviceAgentDAO.setContactEmail("joe.smith#arwe.com");
serviceAgentDAO.setContactTelephone("0735333333");
serviceAgentDAO.setEnabled(true);
serviceAgentDAO.setFirstNames("Joe");
serviceAgentDAO.setLastName("Smith");
serviceAgentDAO.setServiceDefinitionIds(Arrays.asList(UUID.fromString("9a9cb34a-4221-11e8-842f-0ed5f89f718b")));
assignmentDAO.setId(UUID.fromString("69f7cd9c-423f-11e8-842f-0ed5f89f718b"));
assignmentDAO.setCustomerId(UUID.fromString("7b479d52-423f-11e8-842f-0ed5f89f718b"));
assignmentDAO.setCustomerName("John Gill");
assignmentDAO.setServiceAgentId(UUID.fromString("e5cec1dc-422b-11e8-842f-0ed5f89f718b"));
assignmentDAO.setServiceDefinitionId(UUID.fromString("9a9cb34a-4221-11e8-842f-0ed5f89f718b"));
assignmentDAO.setServiceSlotId(UUID.fromString("a7ff6543-4236-11e8-8706-313df4405fc7"));
assignmentDAO.setVehicle("WIN898987686");
/*when(serviceAgentRepository.findOne(BasicMapId.id("id", Mockito.any(UUID.class)))).thenAnswer(new Answer() {
#Override
public ServiceAgentDAO answer(InvocationOnMock invocationOnMock) throws Throwable {
System.out.println("ARGUMENT IS OUTSIDE :: "+(String)invocationOnMock.getArguments()[0]);
if(((String)invocationOnMock.getArguments()[0]).equals(UUID.fromString("e5cec1dc-422b-11e8-842f-0ed5f89f718b"))) {
System.out.println("ARGUMENT IS :: "+invocationOnMock.getArguments()[0]);
return serviceAgentDAO;
}
else
throw new NotFoundException("The Service Agent ID does not exist!");
}
}
);*/
//when(serviceAgentRepository.findOne(BasicMapId.id("id", AdditionalMatchers.not(Matchers.eq(UUID.fromString("e5cec1dc-422b-11e8-842f-0ed5f89f718b")))))).thenThrow (new NotFoundException("The ServiceAgent with that ID does not exist!"));
when(serviceAgentRepository.findOne(BasicMapId.id("id", UUID.class))).thenReturn (serviceAgentDAO);
List<AssignmentDAO> assignmentDAOList = Arrays.asList(assignmentDAO);
when(assignmentRepository.findByServiceAgentId(UUID.fromString("e5cec1dc-422b-11e8-842f-0ed5f89f718b"))).thenReturn(assignmentDAOList);
assignmentDAO.setServiceAgentId(null);
when(assignmentRepository.save(Mockito.any(AssignmentDAO.class))).thenReturn(assignmentDAO);
serviceAgentDAO.setEnabled(false);
when(serviceAgentRepository.save(Mockito.any(ServiceAgentDAO.class))).thenReturn(serviceAgentDAO);
}
#Test
public void testServiceAgentNotFound() throws Exception {
ObjectMapper objectMapper = JacksonConfig.createMapper();
ServiceAgentDTO serviceAgentDTO = new ServiceAgentDTO();
serviceAgentDTO.setEnabled(false);
this.mockMvc.perform(patch("/serviceagent/" + UUIDs.timeBased())
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(serviceAgentDTO))).andDo(print())
.andExpect(status().isNotFound());
}
#Test
public void testServiceAgentIDNotAllowedInRequest() throws Exception {
ObjectMapper objectMapper = JacksonConfig.createMapper();
ServiceAgentDTO serviceAgentDTO = new ServiceAgentDTO();
serviceAgentDTO.setId(UUIDs.timeBased());
serviceAgentDTO.setEnabled(false);
this.mockMvc.perform(patch("/serviceagent/" + UUIDs.timeBased())
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(serviceAgentDTO))).andDo(print())
.andExpect(status().isBadRequest());
}
/*
test to verify if the agent is disabled, then the agent is removed on his assignments as well
*/
#Test
public void testServiceAgentDisabledFromEnabled() throws Exception {
ObjectMapper objectMapper = JacksonConfig.createMapper();
// add a service provider
serviceProviderDAO.setId(UUID.fromString("8890e560-4170-11e8-a465-3f3e0c8fed10"));
serviceProviderDAO.setContactAddress("Torsgatan 190");
serviceProviderDAO.setContactTelephone("073q12345678");
serviceProviderDAO.setEnabled(true);
serviceProviderDAO.setName("Cleany Car");
// add a service type
serviceTypeDAO.setId(UUID.fromString("e3e0c006-4220-11e8-842f-0ed5f89f718b"));
serviceTypeDAO.setEnabled(true);
serviceTypeDAO.setName("Refuel Benzene 95");
serviceTypeDAO.setParentServiceTypeId(UUID.fromString("c1ecdf7a-4220-11e8-842f-0ed5f89f718b"));
serviceTypeDAO.setScopes(Arrays.asList("UNLOCK", "LOCK"));
// add service definition
serviceDefinitionDAO.setId(UUID.fromString("9a9cb34a-4221-11e8-842f-0ed5f89f718b"));
serviceDefinitionDAO.setEnabled(true);
serviceDefinitionDAO.setGeographicAvailability(null);
serviceDefinitionDAO.setLeadTimesInHours(24);
serviceDefinitionDAO.setMaxAdvanceTimeInDays(7);
Map<Integer, String> operatingWeekMap = new HashMap<>();
operatingWeekMap.put(1, "10:00&17:00");
operatingWeekMap.put(2, "09:00&17:00");
operatingWeekMap.put(3, "09:00&17:00");
operatingWeekMap.put(4, "09:00&17:00");
operatingWeekMap.put(5, "09:00&17:00");
operatingWeekMap.put(6, "11:00&17:00");
operatingWeekMap.put(7, "09:00&17:00");
serviceDefinitionDAO.setOperatingWeek(operatingWeekMap);
serviceDefinitionDAO.setServiceProviderId(UUID.fromString("8890e560-4170-11e8-a465-3f3e0c8fed10"));
serviceDefinitionDAO.setServiceSlotDurationInMinutes(60);
serviceDefinitionDAO.setServiceTypeId(UUID.fromString("e3e0c006-4220-11e8-842f-0ed5f89f718b"));
serviceDefinitionDAO.setTimeZoneId("Europe/London");
// we do not populate service slot as of now, since we just need to disable agent!
ServiceAgentDTO serviceAgentDTO = new ServiceAgentDTO();
serviceAgentDTO.setEnabled(false);
this.mockMvc.perform(patch("/serviceagent/" + UUID.fromString("e5cec1dc-422b-11e8-842f-0ed5f89f718b"))
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(serviceAgentDTO))).andDo(print())
.andExpect(status().isOk());
}
}
The ServiceAgentService class has the constructor injection already for the repositories.
For some reason my mocked repositories in the setup() method do not take effect.
Also, the BaseTest class looks like below
package se.volvo.spp;
import org.junit.Ignore;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.SpringRunner;
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
classes = Application.class)
#AutoConfigureMockMvc
#ActiveProfiles("dev")
#Ignore
public class BaseTest {
}
Any help is highly appreciated!

Managing google cloud instances using jcloud api

I want to add and list all the instances/VM under my project in google cloud using Jcloud api. In this code, I am assuming a node to be an instance.
I have set all the variables as required and extracted the private key from the json file. The context build takes place successfully.
images = compute.listImages() => lists all the images provided by google.
nodes = compute.listNodes() =>should list nodes but instead give null pointer exception.
Output=>
No of images 246
Exception in thread "main" java.lang.NullPointerException: group
at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:229)
at org.jclouds.compute.internal.FormatSharedNamesAndAppendUniqueStringToThoseWhichRepeat.checkGroup(FormatSharedNamesAndAppendUniqueStringToThoseWhichRepeat.java:124)
at org.jclouds.compute.internal.FormatSharedNamesAndAppendUniqueStringToThoseWhichRepeat.sharedNameForGroup(FormatSharedNamesAndAppendUniqueStringToThoseWhichRepeat.java:120)
at org.jclouds.googlecomputeengine.compute.functions.FirewallTagNamingConvention$Factory.get(FirewallTagNamingConvention.java:39)
at org.jclouds.googlecomputeengine.compute.functions.InstanceToNodeMetadata.apply(InstanceToNodeMetadata.java:68)
at org.jclouds.googlecomputeengine.compute.functions.InstanceToNodeMetadata.apply(InstanceToNodeMetadata.java:43)
at com.google.common.base.Functions$FunctionComposition.apply(Functions.java:211)
at com.google.common.collect.Iterators$8.transform(Iterators.java:794)
at com.google.common.collect.TransformedIterator.next(TransformedIterator.java:48)
at com.google.common.collect.Iterators$7.computeNext(Iterators.java:646)
at com.google.common.collect.AbstractIterator.tryToComputeNext(AbstractIterator.java:143)
at com.google.common.collect.AbstractIterator.hasNext(AbstractIterator.java:138)
at com.google.common.collect.Iterators.addAll(Iterators.java:356)
at com.google.common.collect.Iterables.addAll(Iterables.java:350)
at com.google.common.collect.Sets.newLinkedHashSet(Sets.java:328)
at org.jclouds.compute.internal.BaseComputeService.listNodes(BaseComputeService.java:335)
at org.jclouds.examples.compute.basics.Example.main(Example.java:54)
package org.jclouds.examples.compute.basics;
import static com.google.common.base.Charsets.UTF_8;
import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_SCRIPT_COMPLETE;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.jclouds.ContextBuilder;
import org.jclouds.compute.ComputeService;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.domain.ComputeMetadata;
import org.jclouds.compute.domain.Image;
import org.jclouds.domain.Credentials;
import org.jclouds.enterprise.config.EnterpriseConfigurationModule;
import org.jclouds.googlecloud.GoogleCredentialsFromJson;
import org.jclouds.logging.slf4j.config.SLF4JLoggingModule;
import org.jclouds.sshj.config.SshjSshClientModule;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableSet;
import com.google.common.io.Files;
import com.google.inject.Module;
public class Example {
public static void main(String[] args)
{
String provider = "google-compute-engine";
String identity = "***#developer.gserviceaccount.com";
String credential = "path to private key file ";
credential = getCredentialFromJsonKeyFile(credential);
Properties properties = new Properties();
long scriptTimeout = TimeUnit.MILLISECONDS.convert(20, TimeUnit.MINUTES);
properties.setProperty(TIMEOUT_SCRIPT_COMPLETE, scriptTimeout + "");
Iterable<Module> modules = ImmutableSet.<Module> of(
new SshjSshClientModule(),new SLF4JLoggingModule(),
new EnterpriseConfigurationModule());
ContextBuilder builder = ContextBuilder.newBuilder(provider)
.credentials(identity, credential)
.modules(modules)
.overrides(properties);
ComputeService compute=builder.buildView(ComputeServiceContext.class).getComputeService();
Set<? extends Image> images = compute.listImages();
System.out.printf(">> No of images %d%n", images.size());
Set<? extends ComputeMetadata> nodes = compute.listNodes();
System.out.printf(">> No of nodes/instances %d%n", nodes.size());
compute.getContext().close();
}
private static String getCredentialFromJsonKeyFile(String filename) {
try {
String fileContents = Files.toString(new File(filename), UTF_8);
Supplier<Credentials> credentialSupplier = new GoogleCredentialsFromJson(fileContents);
String credential = credentialSupplier.get().credential;
return credential;
} catch (IOException e) {
System.err.println("Exception reading private key from '%s': " + filename);
e.printStackTrace();
System.exit(1);
return null;
}
}
}

How to specify classpath ordering in Gradle

I need to control the ordering of jars in the testRuntime configuration.
I must make sure that robolectric-x.x.jar comes before android.jar, or else I get the dreaded RuntimeException("Stub!").
How do I do that?
Here is my complete build.gradle for running Robolectric tests against my Android app, which uses RoboGuice:
apply plugin: 'java'
androidJar = new File(System.getenv('ANDROID_HOME'), '/platforms/android-7/android.jar')
configurations { robo }
dependencies {
robo('com.pivotallabs:robolectric:1.0-RC1')
testCompile('org.roboguice:roboguice:1.1.2')
testCompile('junit:junit:4.8.2')
testCompile project (':app')
testCompile files(androidJar)
}
sourceSets.test.compileClasspath = configurations.robo + sourceSets.test.compileClasspath
sourceSets.test.runtimeClasspath = configurations.robo + sourceSets.test.runtimeClasspath
test {
excludes = ['**/MyRobolectricTestRunner.class']
}
I had to add an exclusion for the test runner, or else Gradle will throw an exception.
MyRobolectricTestRunner.java looks like this:
package com.acme.myapp;
import java.io.File;
import org.junit.runners.model.InitializationError;
import roboguice.application.RoboApplication;
import roboguice.inject.ContextScope;
import com.google.inject.Injector;
import com.xtremelabs.robolectric.Robolectric;
import com.xtremelabs.robolectric.RobolectricTestRunner;
public class MyRobolectricTestRunner extends RobolectricTestRunner {
public MyRobolectricTestRunner(Class<?> testClass) throws InitializationError {
// Tell Robolectric where to find AndroidManifest.xml and res/
super(testClass, new File("../app"));
}
/**
* Enable injection into tests as well...
*/
#Override
public void prepareTest(Object test) {
RoboApplication myApplication = (RoboApplication) Robolectric.application;
Injector injector = myApplication.getInjector();
ContextScope contextScope = injector.getInstance(ContextScope.class);
contextScope.enter(myApplication);
injector.injectMembers(test);
}
}
And here's a sample test that illustrates injection:
package com.acme.myapp;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import roboguice.inject.InjectResource;
#RunWith(MyRobolectricTestRunner.class)
public class StringFormattingTest {
#InjectResource(R.string.info_pending_amount)
private String pendingAmountPattern;
#Test
public void testFormatInfoPendingAmount() {
String s = String.format(pendingAmountPattern, 20.0d, "EUR");
assertEquals("Only a part of your stake (20,00 EUR) was accepted", s);
}
}
This might work:
configurations { robo }
dependencies {
robo ...
testRuntime ...
}
sourceSets.test.runtimeClasspath = configurations.robo + sourceSets.test.runtimeClasspath