How to mock constructor with methods as an parameter using EasyMock? - easymock

I want to test method "make()" using EasyMock. Inside a method there is a new object created with parameters. I wanted to know, how to write test case for the same using EasyMock ?
private void make(final Parent p) {
fun = new Fun(getMethod1(), getMethod2(), getMethod3(), getMethod4());
fun.setBorder(120);
p.add(fun);
}
private ProductSpecification getMethod1() {
return getSequence();
}
//XYZ.class
#Override
public T getSequence() {
return this.sequence;
}
public View getMethod2() {
return view;
}
public Info getMethod3() {
return this.info;
}
Any help would be appreciated.
Thanks.

You can't directly do it with EasyMock. Some will tell you that you can mock the instantiation using PowerMock.
But it generally means a flaw in your design. I personally never use PowerMock.
The questions to ask are:
Do I really need to mock that instantiation? If it's just some data, it's probably not needed
If I need to, should I extract a class or a method?
The answer to question 2 depends on how you will use it later.
If I extract a class, I will have
private final FunFactory funFactory;
private void make(Parent p) {
fun = funFactory.create(getMethod1(), getMethod2(), getMethod3(), getMethod4());
fun.setBorder(120);
p.add(fun);
}
#Test
public void test() {
Fun fun = mock(Fun.class);
FunFactory funFactory = mock(FunFactory.class);
expect(funFactory.create("m1", "m2", "m3", "m4")).andReturn(fun);
replay(fun, funFactory);
// do the test
}
And if I extract a method, I will have the following.
private void make(Parent p) {
fun = createFun(getMethod1(), getMethod2(), getMethod3(), getMethod4());
fun.setBorder(120);
p.add(fun);
}
Fun createFun(String m1, String m2, String m3, String m4) {
return new Fun(m1, m2, m3, m4);
}
#Test
public void test() {
Fun fun = mock(Fun.class);
Make make = partialMockBuilder(Make.class)
.addMockedMethod("createFun")
.createMock();
expect(make.createMock("m1", "m2", "m3", "m4")).andReturn(fun);
replay(fun, make);
// do the test
}

Related

testng how to dynamically set groups from Factory?

Before I setup a test class like the code below:
1. the Factory and test Dataprovider both used excel as the dataprovider.
2. In the Factory dataprovider table, it has a list of url
3. Each time, it will find one of the url in the factory dataprovider table, and run the test in each test methods..
public class Test {
WebDriver driver;
private String hostName;
private String url;
#Factory(dataProvider = "xxxx global variables", dataProviderClass = xxxx.class)
public GetVariables(String hostName, String url) {
this.hostName = hostName;
this.url = url;
}
#BeforeMethod
#Parameters("browser")
public void start(String browser) throws Exception {
driver = new FirefoxDriver();
driver.get(url);
Thread.sleep(1000);
}
#Test(priority = 10, dataProvider = "dataprovider Test A", dataProviderClass = xxx.class)
public void TestA(Variable1,
Variable2,Variable3) throws Exception {
some test here...
}
#Test(priority = 20, dataProvider = "dataprovider Test B", dataProviderClass = xxx.class)
public void TestB(Variable1,
Variable2,Variable3)
throws Exception {
some test here...
}
#AfterMethod
public void tearDown() {
driver.quit();
}
Now I want to dynamically assign different group for each test for different url. I am thinking add a variable 'flag' in the #Factory dataprovider:
#Factory(dataProvider = "xxxx global variables", dataProviderClass = xxxx.class)
public GetVariables(String hostName, String url, String flag) {
this.hostName = hostName;
this.url = url;
this.flag = flag;
}
That when flag.equals("A"), it will only run test cases in test groups={"A"}.
When flag.equals("B"), it will only run test cases in test groups ={"B"},
When flag.equals("A,B"), it will only run test cases in test groups ={"A","B"}
Is there any way I can do that?
Thank you!
TestNG groups provides "flexibility in how you partition your tests" but it isn't for conditional test sets. For that you simply use plain old Java.
You can use inheritance or composition (I recommend the latter, see Item 16: Favor composition over inheritance from Effective Java).
Either way the general idea is the same: use a Factory to create your test class instances dynamically creating the appropriate class type with the appropriate test annotations and/or methods that you want to run.
Examples:
Inheritance
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
public class DemoTest {
#Factory
public static Object[] createTests() {
return new Object[]{
new FlavorATest(),
new FlavorBTest(),
new FlavorABTest()
};
}
/**
* Base test class with code for both A-tests and B-tests.
*
* Note that none of these test methods are annotated as tests so that
* subclasses may pick which ones to annotate.
*/
public static abstract class BaseTest {
protected void testA() {
// test something specific to flavor A
}
protected void testB() {
// test something specific to flavor B
}
}
// extend base but only annotate A-tests
public static class FlavorATest extends BaseTest {
#Test
#Override
public void testA() {
super.testA();
}
}
// extend base but only annotate B-tests
public static class FlavorBTest extends BaseTest {
#Test
#Override
public void testB() {
super.testB();
}
}
// extend base and annotate both A-tests and B-tests
public static class FlavorABTest extends BaseTest {
#Test
#Override
public void testA() {
super.testA();
}
#Test
#Override
public void testB() {
super.testB();
}
}
}
Composition
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
public class DemoTest {
#Factory
public static Object[] createTests() {
return new Object[]{
new FlavorATest(),
new FlavorBTest(),
new FlavorABTest()
};
}
private static void testA() {
// test something specific to flavor A
}
private static void testB() {
// test something specific to flavor B
}
// only create A-test methods and delegate to shared code above
public static class FlavorATest {
#Test
public void testA() {
DemoTest.testA();
}
}
// only create B-test methods and delegate to shared code above
public static class FlavorBTest {
#Test
public void testB() {
DemoTest.testB();
}
}
// create A-test and B-test methods and delegate to shared code above
public static class FlavorABTest {
#Test
public void testA() {
DemoTest.testA();
}
#Test
public void testB() {
DemoTest.testB();
}
}
}
Your factory methods won't be as simple as you'll need to use your "flag" from your test data to switch off of and create instances of the appropriate test classes.

Passing a list or array to RESTeasy using get

I've seen this kind of thing described in various examples showing how to create a REST service which takes arrays or a list of objects as part of the URL.
My question is, how to implement this using RESTeasy?
Something like the following would be how i would assume this to work.
#GET
#Path("/stuff/")
#Produces("application/json")
public StuffResponse getStuffByThings(
#QueryParam("things") List<Thing> things);
Create a StringConverter and a use a wrapper object. Here is a quick and dirty example:
public class QueryParamAsListTest {
public static class Thing {
String value;
Thing(String value){ this.value = value; }
}
public static class ManyThings {
List<Thing> things = new ArrayList<Thing>();
ManyThings(String values){
for(String value : values.split(",")){
things.add(new Thing(value));
}
}
}
static class Converter implements StringConverter<ManyThings> {
public ManyThings fromString(String str) {
return new ManyThings(str);
}
public String toString(ManyThings value) {
//TODO: implement
return value.toString();
}
}
#Path("/")
public static class Service {
#GET
#Path("/stuff/")
public int getStuffByThings(
#QueryParam("things") ManyThings things){
return things.things.size();
}
}
#Test
public void test() throws Exception {
Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
dispatcher.getProviderFactory().addStringConverter(new Converter());
dispatcher.getRegistry().addSingletonResource(new Service());
MockHttpRequest request = MockHttpRequest.get("/stuff?things=a,b,c");
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
Assert.assertEquals("3", response.getContentAsString());
}
}
I think you can also use a StringParamUnmarshaller
I had some luck with this, using Collection rather than List. I was unable to make a StringConverter for List work.
#Provider
public class CollectionConverter implements StringConverter<Collection<String>> {
public Collection<String> fromString(String string) {
if (string == null) {
return Collections.emptyList();
}
return Arrays.asList(string.split(","));
}
public String toString(Collection<String> values) {
final StringBuilder sb = new StringBuilder();
boolean first = true;
for (String value : values) {
if (first) {
first = false;
} else {
sb.append(",");
}
sb.append(value);
}
return sb.toString();
}
}
I did the toString from my head. Be sure to write unit tests for it to verify. But of course, everything is easier and clearer when you use Guava. Can use Joiner and Splitter. Really handy.
Just use a wrapper on its own, no need for anything else.
In your endpoint
#Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
#Path("/find")
#GET
MyResponse find(#QueryParam("ids") Wrapper ids);
And you wrapper looks like this :
public class Wrapper implements Serializable {
private List<BigInteger> ids = Collections.emptyList();
public String toString() {
return Joiner.on(",")
.join(ids);
}
public List<BigInteger> get() {
return ids;
}
public Wrapper(String s) {
if (s == null) {
ids = Collections.emptyList();
}
Iterable<String> splitted = Splitter.on(',')
.split(s);
Iterable<BigInteger> ids = Iterables.transform(splitted, Functionz.stringToBigInteger);
this.ids = Lists.newArrayList(ids);
}
public Wrapper(List<BigInteger> ids) {
this.ids = ids;
}
}

Suggest Addresses in a SuggestBox in GWT/Java

I want to define a SuggestBox, which behaves like the search bar in Google Maps: When you begin to type, real addresses, starting with the typed letters, appear.
I think, that I need to use the Geocoder.getLocations(String address, LocationCallback callback) method, but I have no idea how to connect this with the oracle, which is needed by the suggest box to produce its suggestions.
Can you please give me ideas how do I connect the getLocations Method with the SuggestOracle?
I solved this by implementing a subclass of SuggestBox, which has it's own SuggestOracle. The AddressOracle deals as a Wrapper for the Google Maps Service, for which the class Geocoderin the Google Maps API for GWT offers abstractions.
So here is my solution:
First we implement the Widget for a SuggestBox with Google Maps suggestions
public class GoogleMapsSuggestBox extends SuggestBox {
public GoogleMapsSuggestBox() {
super(new AddressOracle());
}
}
Then we implement the SuggestOracle, which wraps the Geocoder async method abstractions:
class AddressOracle extends SuggestOracle {
// this instance is needed, to call the getLocations-Service
private final Geocoder geocoder;
public AddressOracle() {
geocoder = new Geocoder();
}
#Override
public void requestSuggestions(final Request request,
final Callback callback) {
// this is the string, the user has typed so far
String addressQuery = request.getQuery();
// look up for suggestions, only if at least 2 letters have been typed
if (addressQuery.length() > 2) {
geocoder.getLocations(addressQuery, new LocationCallback() {
#Override
public void onFailure(int statusCode) {
// do nothing
}
#Override
public void onSuccess(JsArray<Placemark> places) {
// create an oracle response from the places, found by the
// getLocations-Service
Collection<Suggestion> result = new LinkedList<Suggestion>();
for (int i = 0; i < places.length(); i++) {
String address = places.get(i).getAddress();
AddressSuggestion newSuggestion = new AddressSuggestion(
address);
result.add(newSuggestion);
}
Response response = new Response(result);
callback.onSuggestionsReady(request, response);
}
});
} else {
Response response = new Response(
Collections.<Suggestion> emptyList());
callback.onSuggestionsReady(request, response);
}
}
}
And this is a special class for the oracle suggestions, which just represent a String with the delivered address.
class AddressSuggestion implements SuggestOracle.Suggestion, Serializable {
private static final long serialVersionUID = 1L;
String address;
public AddressSuggestion(String address) {
this.address = address;
}
#Override
public String getDisplayString() {
return this.address;
}
#Override
public String getReplacementString() {
return this.address;
}
}
Now you can bind the new widget into your web page by writing the following line in the onModuleLoad()-method of your EntryPoint-class:
RootPanel.get("hm-map").add(new GoogleMapsSuggestBox());

Parameterized Tests with VS2010 Test Tools

Is it possible to write parameterized tests using VS2010 Test Tools for Silverlight?
In a regular NUnit test this would be done using TestCase attributes...
[Test]
[TestCase("myParam1")]
[TestCase("myParam2")]
[TestCase("myParam3")]
public void TestSomethingWithParameters(string myParam)
{
// ...some tests using myParam
}
Is this possible using VS2010 Test Tools?
No, this is not possible. The next best thing is to use data driven tests e.g.
http://callumhibbert.blogspot.com/2009/07/data-driven-tests-with-mstest.html
Check out the MSDN documentation also.
You can create a base class with the test method and the parameters as virtual properties.
When you inherit from this class you only need to override the properties with the desired values.
Please see the sample code:
public class Operation
{
public static int Add(int x, int y)
{
return x + y;
}
}
[TestClass]
public class AddTests : WorkItemTest
{
protected virtual int First{get { return 0; }}
protected virtual int Second{get { return 0; }}
[TestInitialize]
public virtual void Init()
{
//Init code
}
[TestCleanup]
public virtual void Clean()
{
//Clean code
}
[TestMethod]
[Description("x+y = y+x")]
public virtual void Test_operation_commutativity()
{
Assert.AreEqual(Operation.Add(Second, First), Operation.Add(First, Second));
}
}
[TestClass]
public class AddPositiveTest : AddTests
{
protected override int First { get { return 1; } }
protected override int Second { get { return 2; } }
}
[TestClass]
public class AddNegativeTest : AddTests
{
protected override int First { get { return -1; } }
protected override int Second { get { return -2; } }
}

Dynamic Autosuggest Combobox in GXT

Over the past 5 months we have been prototyping GWT and setting up the infrastructure. WE are using GXT for the widgets with MVP and Command Pattern implementations. However, we are currently looking to do a spike on a ComboBox with autosuggest from a live Database. I would like to do this in the framework of the MVP and Command pattern implementations. Any one out there have any ideas how to go about doing this?
I solved that using a generic DispatchDataProxy modelled over the Command Pattern. Thanks for the link, but GXT documentation leaves a lot to be desired, though the framework is really nice and cool.
I will post the code here `public class DispatchDataProxy implements DataProxy> {
#Inject
private DispatchAsync dispatch ;//= new StandardDispatchAsync(new DefaultExceptionHandler());
#Override
public void load(DataReader<ListLoadResult<X>> reader, Object loadConfig, final AsyncCallback<ListLoadResult<X>> callback) {
if (loadConfig instanceof BasePagingLoadConfig) {
BasePagingLoadConfig a = (BasePagingLoadConfig) loadConfig;
Map<String, Object> map = a.getProperties();
Object data = map.get("query");
XCommand action = new XCommand();
action.setX((String) data);
dispatch.execute(action, new AsyncCallback<XResult>() {
#Override
public void onFailure(Throwable arg0) {
//Log.debug("Some error:" + arg0.getMessage());
callback.onFailure(arg0);
}
#Override
public void onSuccess(XResult arg0) {
ListLoadResult<X> list = arg0.getList();
callback.onSuccess(list);
}
});
}
}
public DispatchAsync getDispatch() {
return dispatch;
}
public void setDispatch(DispatchAsync dispatch) {
this.dispatch = dispatch;
}
}`
Hope its useful. Will appreciate some comments as well
Have you looked here?
http://www.sencha.com/examples-2/explorer.html#advancedcombobox
They show something similar. The issue with GXT is you are better off using their DataProxy because you need to set a ModelData instance.
I found solution for simple combo box, override getValue method:
public SimpleComboBox<String> createEditableSimpleComboBox() {
return new SimpleComboBox<String>() {
#Override
public SimpleComboValue<String> getValue() {
SimpleComboValue<String> v = super.getValue();
String raw = getRawValue();
if ((v == null || v.getValue() == null) && raw != null && !raw.isEmpty()) {
v = new SimpleComboValue<String>(raw){
private static final long serialVersionUID = 1L;
};
}
return v;
}
};
}
Now when you add to combo box default value (not defined in store) method getValue returns this value - not null.

Resources