#parameters in Junit 4 - junit

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;
}
}
}

Related

how to instantiate objects inside the class to be tested is an abstract class in Junit testing?

I have a class below for which I want to write a unit test
abstract class ProductImpl{
#Inject DataServices ds; // using Guice
public Response parse(String key, Long value){
Response res = ds.getResponseObject(); // Response object is created using DataServices object
res.id = key;
res.code = value;
}
}
And I have a test as below
class ProductImplTest{
#InjectMocks ProductImpl impl;
Map<String, Long> map;
#Before
map.put("abc", 10L);
map.put("xyz", 11L);
}
#Test
public void test(){
for(String key: map.keySet()){
Response res = impl.parse(key, map.get(key));
// and check if fields of Response object are set correctly i.e res.id is abc and value is 10L
}
}
But when i debug the test and control goes to parse method , DataServices object ds is null. How to instantiate this object through test . I do not want to use mocking, I want real response objects to be created and test the values set in them.
You can use Mockito
#RunWith(MockitoJUnitRunner.class)
class ProductImplTest {
#Mock DataService dService;
#InjectMocks ProductImpl sut;
#Test
public void test() {
ResponseObject ro = new ResponseObject();
String string = "string";
Long longVal = Long.valueOf(123);
sut.parse("string", longVal);
verify(dService).getResponseObject();
assertThat(ro.getId()).isEqualTo("string");
// you should use setters (ie setId()), then you can mock the ResponseObject and use
// verify(ro).setId("string");
}
}
EDIT:
With ResponseObject being an abstract class or preferably an interface, you'd have
interface ResponseObject {
void setId(String id);
String getId();
// same for code
}
and in your test
#Test public void test() {
ResponseObject ro = mock(ResponseObject.class);
// ... same as above, but
verify(dService).getResponseObject();
verify(ro).setId("string"); // no need to test getId for a mock
}
Try with constructor injection:
class ProductImpl{
DataServices ds;
#Inject
public ProductImpl(DataServices ds) {
this.ds = ds;
}
}

How to mock a void method with no arguments?

For Example:
Class A{
string s = null;
public void method(){
s="Sample String";
}
}
I have a void method with similar scenario. How can I test such void method?
With void methods you should test the interaction with its dependent objects within the void method. I think a void method with no argument is rarely useful to test (but if you have a valid use case, please add it to your question). I provided you a simple example for a method with an argument but void as a return type:
public class A {
private DatabaseService db;
private PaymentService payment;
// constructor
public void doFoo() {
if(n < 2) {
db.updateDatabase();
} else {
payment.payBill();
}
}
}
And the unit test for this can look like the following
#RunWith(MockitoJUnitRunner.class)
public class ATest {
#Mock
DatabaseService db;
#Mock
PaymentService payment;
#Test
public void testDoFooWithNGreaterTwo() {
A cut = new A(db, payment); // cut -> class under test
cut.doFoo(3);
verify(payment).payBill(); // verify that payment was called
}
#Test
public void testDoFooWithNLessThanTwo() {
A cut = new A(db, payment); // cut -> class under test
cut.doFoo(1);
verify(db).updateDatabase(); // verify that db was called
}
}

#ComponentScan JSON information replaces the HTML views

Maybe the title is not the best to explain the problem, but I'll try to explain it as best as possible.
I have an Spring Boot Application using JPA and MySQL, so in order to check everything worked properly, I made a simple CRUD test for my database, and I found problems with autowiring which are explained in my previous question. The solution for those problems was just adding the #ComponentScan annotation to my Application.java.
It was the solution for the test because it run without problems, but then I find another problem. Apart from the test, I need my application to show a list of Proposals made by some Users and also some Comments. Before adding that annotation, the HTMLs showed the correct information, but after adding it shows information about the database in JSON format on the main page and if I try to navigate to "localhost:8080/viewProposal" p.e. it shows a WhiteLabel error page with error code 404. I have no idea why it is replacing the HTMLs because I have just one controller and is not a RESTController. These are my classes:
Application.java
#SpringBootApplication
#EntityScan("persistence.model")
#EnableJpaRepositories("persistence.repositories")
#ComponentScan("services.impl")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
MainController.java
#Controller
#RequestMapping("/")
public class MainController {
private static final Logger logger = Logger.getLogger(MainController.class);
private List<SseEmitter> sseEmitters = Collections.synchronizedList(new ArrayList<>());
private Map<String, Proposal> proposals = generateProposals();
#RequestMapping({"/live","/"})
public String landing(Model model) {
return "index";
}
#RequestMapping("/viewProposal")
public String viewProposal(Model model, Long id) {
//put the object in the map
return "viewProposal";
}
#KafkaListener(topics = "newVote")
public void listen(String data) {
String[] contents = data.split(";");
if(contents.length!=2)
return;
Proposal p;
int newVote;
if (proposals.containsKey(contents[0]))
p = proposals.get(contents[0]);
else {
p = new Proposal();
p.setTitle(contents[0]);
proposals.put(p.getTitle(), p);
}
if (contents[1].equals("+"))
newVote = +1;
else if (contents[1].equals("-"))
newVote = -1;
else
newVote = 0;
p.setNumberOfVotes(p.getNumberOfVotes() + newVote);
logger.info("New message received: \"" + data + "\"");
}
private static Map<String, Proposal> generateProposals() {
Map<String, Proposal> lista = new HashMap<String, Proposal>();
Proposal p = new Proposal();
p.setTitle("tituloPrueba");
lista.put("tituloPrueba", p);
return lista;
}
#ModelAttribute("proposals")
public Map<String, Proposal> getProposals() {
return proposals;
}
public void setProposals(Map<String, Proposal> proposals) {
this.proposals = proposals;
}
}
MvcConfiguration
#Configuration
#EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter{
#Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/resources/templates/");
resolver.setSuffix(".html");
return resolver;
}
#Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.defaultContentType(MediaType.TEXT_HTML);
}
}
If you want to see the rest of the classes, please go to my previous question everything is in there.
Thanks in advance.

Jackson readValue mapping to overloaded java class problem

I have some JSON where one of the keys has one of three values: an int, a string, or a json object. Using the snippet below I can map this field when it is an int or a string but fail when it's a json object. Where am I going wrong? What should I be doing?
The JSON value key looks like:
"value": 51,
or
"value": 51,
or (and this is where I am having trouble)
"value": {"lat": 53.990614999999998, "lng": -1.5391117000000301, "addr": "Harrogate, North Yorkshire, UK"}
public class Test {
public Test() {
}
public static class Value {
public int slidervalue;
public String voicevalue;
public GeoValue geovalue; // problem
public Value(int value) {
this.slidervalue = value
}
public Value(String value) {
this.voicevalue = value;
}
public Value(JSONObject value) {
JSONObject foo = value; // this is never reached
this.geovalue = value; // and how would this work so as map value to a GeoValue?
}
private static class GeoValue {
private double _lat;
private double _lng;
private String _addr;
public float getLat() {
return (float)_lat;
}
public void setLat(float lat) {
_lat = (double)lat;
}
public float getLng() { return (float)_lng;}
public void setLng(float lng) { _lng = (double)lng; }
public String getAddr() { return _addr;}
public void setAddr(String addr) { _addr = addr; }
}
} // end of Value class
public Value getValue() { return _value;}
public void setValue(Value value) {
_value = value;
}
} //end of Test class
and this is being used like this:
ObjectMapper mapper = new ObjectMapper();
instance = mInstances.getJSONObject(i).toString();
Test testinstance = mapper.readValue(instance, Test.class);
public class Test {
public Test() {
}
public static class Value {
public int slidervalue;
public String voicevalue;
public GeoValue geovalue; // problem
public Value(int value) {
this.slidervalue = value
}
public Value(String value) {
this.voicevalue = value;
}
public Value(JSONObject value) {
JSONObject foo = value; // this is never reached
this.geovalue = value; // and how would this work so as map value to a GeoValue?
}
private static class GeoValue {
private double _lat;
private double _lng;
private String _addr;
public float getLat() {
return (float)_lat;
}
public void setLat(float lat) {
_lat = (double)lat;
}
public float getLng() { return (float)_lng;}
public void setLng(float lng) { _lng = (double)lng; }
public String getAddr() { return _addr;}
public void setAddr(String addr) { _addr = addr; }
}
} // end of Value class
public Value getValue() { return _value;}
public void setValue(Value value) {
_value = value;
}
} //end of Test class
and this is being used like this:
ObjectMapper mapper = new ObjectMapper();
instance = mInstances.getJSONObject(i).toString();
Test testinstance = mapper.readValue(instance, Test.class);
This fails with a JSONMappingException: No suitable contructor found for type ... 'value'
Thanks. Alex
What might work is that you mark the constructor that takes JSONObject with #JsonCreator, but do NOT add #JsonProperty for the single parameter. In that case, incoming JSON is bound to type of that parameter (in this case JSONObject, but you could use Map as well), and passed to constructor.
Overloading still works because of special handling for single-string/int/long-argument constructor.
I am not sure if that is the cleanest solution; it might be cleanest to just implement custom deserializer. But it should work.
If your code is what you want, your json should be like this:
{"value":{"slidervalue":1,"voicevalue":"aa","geovalue":{"lat":53.990615,"lng":-1.53911170000003,"addr":"Harrogate, North Yorkshire, UK"}}}

Unmarshalling JSON array via Jettison/Resteasy

Ran into a similar problem like the following forum post:
http://jersey.576304.n2.nabble.com/parsing-JSON-with-Arrays-using-Jettison-td5732207.html
Using Resteasy 2.0.1GA with Jettison 1.2 and getting a problem marshalling arrays when involving namespace mappings. See code below. Basically if the number of array entries are greater than one and namespace mappings are used. Anybody else run into this problem? The Nabble form poster got around it by writing a custom unmarshaller.
I either need to isolate the Jettison bug or write a Resteasy extension of the JettisonMappedUnmarshaller class (which hands over the namespace mappings and unmarshaller to the Jettison Configuration).
The following code doesn't unmarshall (post step) if the properties variables contains 2 or more entries.
public class Experimenting {
#Path("test")
public static class MyResource {
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "Property", propOrder = { "name", "value" })
public static class MyProperty {
#XmlElement(name = "Name", required = true)
protected String name;
#XmlElement(name = "Value", required = true)
protected String value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
#XmlType(name = "MyElement", propOrder = { "myProperty" })
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement(name = "MyElement", namespace = "http://www.klistret.com/cmdb/ci/commons")
#Mapped(namespaceMap = { #XmlNsMap(namespace = "http://www.klistret.com/cmdb/ci/commons", jsonName = "com.klistret.cmdb.ci.commons") })
public static class MyElement {
#XmlElement(name = "MyProperty", namespace = "http://www.klistret.com/cmdb/ci/commons")
protected List myProperty;
public List getMyProperty() {
if (myProperty == null) {
myProperty = new ArrayList();
}
return this.myProperty;
}
public void setMyProperty(List myProperty) {
this.myProperty = myProperty;
}
}
#GET
#Path("myElement/{id}")
#Produces(MediaType.APPLICATION_JSON)
public MyElement getMy(#PathParam("id")
Long id) {
MyElement myElement = new MyElement();
MyProperty example = new MyProperty();
example.setName("example");
example.setValue("of a property");
MyProperty another = new MyProperty();
another.setName("another");
another.setValue("just a test");
MyProperty[] properties = new MyProperty[] { example, another };
myElement.setMyProperty(Arrays.asList(properties));
return myElement;
}
#POST
#Path("/myElement")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public MyElement createMy(MyElement myElement) {
List properties = myElement.getMyProperty();
System.out.println("Properties size: " + properties.size());
return myElement;
}
}
private Dispatcher dispatcher;
#Before
public void setUp() throws Exception {
// embedded server
dispatcher = MockDispatcherFactory.createDispatcher();
dispatcher.getRegistry().addPerRequestResource(MyResource.class);
}
#Test
public void getAndCreate() throws URISyntaxException,
UnsupportedEncodingException {
MockHttpRequest getRequest = MockHttpRequest.get("/test/element/44");
MockHttpResponse getResponse = new MockHttpResponse();
dispatcher.invoke(getRequest, getResponse);
String getResponseBodyAsString = getResponse.getContentAsString();
System.out.println(String.format(
"Get Response code [%s] with payload [%s]", getResponse
.getStatus(), getResponse.getContentAsString()));
MockHttpRequest postRequest = MockHttpRequest.post("/test/element");
MockHttpResponse postResponse = new MockHttpResponse();
postRequest.contentType(MediaType.APPLICATION_JSON);
postRequest.content(getResponseBodyAsString.getBytes("UTF-8"));
dispatcher.invoke(postRequest, postResponse);
System.out.println(String.format(
"Post Response code [%s] with payload [%s]", postResponse
.getStatus(), postResponse.getContentAsString()));
}
}
Do you have to use Jettison? If not I would recommend just switching to use Jackson instead; this typically solves array/list related problems (problem with Jettison is that it converts to XML model, which makes it very hard to tell arrays from objects -- there are bugs, too, but it is fundamentally hard thing to get working correctly).