How to cache a JUnit class field between runs with #Parameters - java

Lets assume the following JUnit test class:
#RunWith(Parameterized.class)
public class MyTestClass {
private ExpensiveObjectToCreate myObject;
#Parameters
public static Collection<Object[]> data() {
Object[][] data = new Object[][] {
{ "parameter1" },
{ "parameter2" },
};
return Arrays.asList(data);
}
#Test
public void test1() {
}
#Test
public void test2() {
}
public MyTestClass(String stringParameter) {
myObject = new ExpensiveObjectToCreate(stringParameter);
}
}
Is there any way for me to create the expensive object just once for every parameter set? I say this because JUnit creates a new test class for every test it needs to run. This means that the expensive object is NOT created 2 times, but actually 4 times (2 parameter sets x 2 tests). This gets even worse when we have many test methods.
Also, sending the expensive object as a parameter is not a solution for me because my scenario is a little bit more complicated (I create the expensive object in JUnit rules).

Why not just roll out a custom cacher in your test case class, which caches the instance created per parameter and returns the same instance on further invocations.
#RunWith(Parameterized.class)
public class Test {
private static ExpensiveObjectCacher cacher; //instance which caches parameter instance
private ExpensiveObject myObject;
public Test(String value) {
this.myObject = cacher.get(value);
}
#BeforeClass
public static void setUpBeforeClass(){
cacher = new ExpensiveObjectCacher();
}
#Parameters
public static Collection<Object[]> data() {
Object[][] data = new Object[][] {
{ "parameter1" },
{ "parameter2" },
};
return Arrays.asList(data);
}
#org.junit.Test
public void test1(){
}
#org.junit.Test
public void test2(){
}
}
//caching for test cases.
class ExpensiveObjectCacher{
private Map<String, ExpensiveObject> map = new ConcurrentHashMap<String, ExpensiveObject>();
ExpensiveObject get(String value){
ExpensiveObject instance = map.get(value);
if(instance == null){
instance = new ExpensiveObject(value);
map.put(value, instance);
}
return instance;
}
}
class ExpensiveObject{
public ExpensiveObject(String value) {
System.out.println("Instance created: " + value);
}
}
Output:
Instance created: parameter1
Instance created: parameter2

You could work with a static Map from the parameters (here a simple string) to instances of ExpensiveObjectToCreate.
#RunWith(Parameterized.class)
public fnial class MyTestClass {
private static final Map<Parameter, ExpensiveObjectToCreate> MAPPING = new HashMap<>();
private ExpensiveObjectToCreate myEOTC;
public MyTestClass(String stringParameter) {
myEOTC = getEOTC(new Parameter(stringParameter));
}
private static getEOTC(Parameter parameter) {
ExpensiveObjectToCreate eotc = MAPPING.get(parameter);
if (eotc == null) {
eotc = new ExpensiveObjectToCreate(parameter.stringParameter);
MAPPING.put(parameter, eotc);
}
rturn eotc;
}
private static final class Parameter {
String stringParameter;
Parameter(String stringParameter) { this.stringParameter = stringParameter; }
#Override public int hashCode() { ... }
#Override public boolean equals(Object other) { ... }
}
}
However, if you also need to limit the number of expensive objects, you should do more work, for example a cache could be a solution.

If you're using Junit 4:
private static ExpensiveObjectToCreate myObject;
private static String stringParameter = "some text";
#BeforeClass
public static void setUpBeforeClass() throws Exception {
myObject = new ExpensiveObjectToCreate(stringParameter);
}
If Junit 3:
private static ExpensiveObjectToCreate myObject;
private static String stringParameter = "some text";
#BeforeClass
protected static void setUpBeforeClass() throws Exception {
myObject = new ExpensiveObjectToCreate(stringParameter);
}
In both cases the object will be created once for all the unit tests.
Edit: The String I am not sure where it came from, so I am asuming that the String is the same for all unit tests.

Related

Spy an already initialized Java object Mockito

I am using the Mocktio library to write some test cases, since I have an elaborate inhertance structure, I have a few objects which are instantiated in the parent class, and I would like to mock one of its function call. Does Mockito library provide any way to spy on a already initialized object?
Also, the object is not directly instantiable.
Similar to the following -
public class A {
protected static MyObject a;
public static void someMethod() {
a = myObjectBuilder.createObj();
}
}
And another class B looks something similar to
class B extends A {
#BeforeClass
public static void setUpBeforeClass() {
someMethod();
}
#Test
public void mockTest() {
// now mock behavior of some method of MyObject a
// Missing line to spy object a.
Mockito.doReturn(false).when(a).xyz();
/* Now call some method that triggers a.xyz()
again, it is not a direct call,
there are multiple layer of abstraction
*/
}
}
Edit: I have tried the following and it does not work
MyObject mock_object = Mockito.spy(a);
Mockito.doReturn(false).when(mock_object).xyz();
Basically, don't do initialisation in BeforeClass, it runs only once but
you need to have new spy in each test, or you must "reinitialise" spy object
before each test.
Please examine this code:
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mockito;
import static org.assertj.core.api.Assertions.assertThat;
class MyObject{
public String cos;
public MyObject(String cos) {
this.cos = cos;
}
public boolean xyz() {
return true;
}
}
class A {
protected static MyObject a;
public void someMethod() {
a = new MyObject("cccc");
}
}
public class B extends A {
#Before
public void setUpBeforeTest() {
someMethod();
}
#Test
public void mockTest() {
MyObject mock_object = Mockito.spy(a);
Mockito.doReturn(false).when(mock_object).xyz();
assertThat(mock_object.xyz()).isFalse();
}
#Test
public void mockTest2() {
MyObject mock_object = Mockito.spy(a);
Mockito.doReturn(true).when(mock_object).xyz();
assertThat(mock_object.xyz()).isTrue();
}
}
If you want it your way, please change:
public void someMethod() {
a = myObjectBuilder.createObj();
}
into:
public static void someMethod() {
a = myObjectBuilder.createObj();
}
You can't call non static method from static initialiser #BeforeClass:
class A {
protected static MyObject a;
public static void someMethod() {
a = new MyObject("cccc");
}
}
public class B extends A {
#BeforeClass
public static void setUpBeforeClass() {
someMethod();
}
#Test
public void mockTest() {
MyObject mock_object = Mockito.spy(a);
Mockito.doReturn(false).when(mock_object).xyz();
assertThat(mock_object.xyz()).isFalse();
}
#Test
public void mockTest2() {
MyObject mock_object = Mockito.spy(a);
// Here we replace original object with our spy
A.a = mock_object;
Mockito.doReturn(false).when(mock_object).xyz();
assertThat(a.xyz()).isFalse();
}
}
Another example (in this case we replace object a with mock (spy is not needed):
class MyObject{
public String cos;
public MyObject(String cos) {
this.cos = cos;
}
public boolean xyz() {
return true;
}
}
class A {
protected MyObject a;
public A() {
a = new MyObject("ggggg");
}
public String doSomethingWithA(){
if(a.xyz()){
return a.cos;
}
else{
return "aaaa";
}
}
}
#RunWith(MockitoJUnitRunner.class)
public class B {
#Mock
MyObject mock_object;
#InjectMocks
A systemUnderTest = new A();
#Test
public void mockTest1() {
Mockito.doReturn(false).when(mock_object).xyz();
assertThat(systemUnderTest.doSomethingWithA()).isEqualTo("aaaa");
}
#Test
public void mockTest2() {
Mockito.doReturn(true).when(mock_object).xyz();
assertThat(systemUnderTest.doSomethingWithA()).isNull();
}
}

Unit Testing with modifying static variables during initialization

I have a class that has static variables assigned during initialization. I would like to write unit tests for this class with modifying values for this static variable. Below is a simple code to explain my scenario
Class to test:
public class Hello {
private final static String HELLO_FINAL = "Hello " + HelloTo.getInstance().getHelloTo(); // I would like to modify this value between tests
public String sayHello() {
return HELLO_FINAL;
}
}
Supporting class:
public class HelloTo {
private String helloTo = "World";
private static HelloTo singleton = new HelloTo();
private HelloTo() {}
public static HelloTo getInstance() {
return singleton;
}
public void setHelloTo(String helloTo) {
this.helloTo = helloTo;
}
public String getHelloTo() {
return helloTo;
}
}
Test class:
import org.junit.Assert;
import org.junit.Test;
public class HelloTest {
#Test
public void testDefault() {
Assert.assertEquals("Hello World", new Hello().sayHello());
}
#Test
public void testDynamic() {
HelloTo.getInstance().setHelloTo("My name");
Assert.assertEquals("Hello My name", new Hello().sayHello());
}
}
Is there a way to make both tests successful. Currently I get a failure for testDymanic() saying:
org.junit.ComparisonFailure: expected:<Hello [World]> but was:<Hello [My name]>
Thanks in advance!
Using a mutable singleton in a tests is an known problem. You have to reset the state of the singleton between tests, of even better, don't use a singleton in your tests.
You could do something like:
public enum HelloTo {
INSTANCE;
private String helloTo = "World";
public void reset() {
setHelloTo("World");
}
public void setHelloTo(String helloTo) {
this.helloTo = helloTo;
}
public String getHelloTo() {
return helloTo;
}
}
public class Hello {
public static String sayHello() {
// has to be dynamic as helloTo can change.
return "Hello " + HelloTo.INSTANCE.getHelloTo();
}
}
public class HelloTest {
#Before
public void setUp() {
HelloTo.INSTANCE.reset();
}
#Test
public void testDefault() {
Assert.assertEquals("Hello World", Hello.sayHello());
}
#Test
public void testDynamic() {
HelloTo.INSTANCE.setHelloTo("My name");
Assert.assertEquals("Hello My name", Hello.sayHello());
}
}
HELLO_FINAL is only initialized once per run; you can't reinitialize it within the same JVM. Is there a way to make both tests successful? Sure, there are countless ways. But that depends on what you're trying to test, which is not completely clear from your example.

Mocking simple property access with JMockIt

I have a simple get-set interface:
public interface Foo {
void setBaz(String baz);
String getProcessedBaz();
}
This interface is a dependency of my actual class under test. I'm trying to mock out Foo to have this effective behavior:
public class MockedFoo implements Foo {
private String bazField;
#Override
public void setBaz(String baz) {
bazField = baz;
}
#Override
public String getProcessedBaz() {
return "PROCESSED_" + bazField;
}
}
So my expected result is:
mockedFoo.setBaz("ABC");
assertEquals("PROCESSED_ABC", mockedFoo.getProcessedBaz());
I was able to capture the method argument using withCapture in a Verification, but how do I set up an Expectation with that same input value? It seems you can do either one or the other.
Is there a way to express this in JMockIt? I'm using the latest version (1.9).
NOTE: I'm aware that I can simply set up a Mockup<Foo> instance and put in all the code above. However, my real code is much more complex and I would prefer not to hand-craft the entire mock class.
You can do this using Delegate. You may try this
Class to test
public interface Foo {
void setBaz(String baz);
String getProcessedBaz();
}
class FooSubClass implements Foo {
private String bazField;
#Override
public void setBaz(String baz) {
bazField = null;
}
#Override
public String getProcessedBaz() {
return bazField;
}
}
Test class
import mockit.Capturing;
import mockit.Deencapsulation;
import mockit.Delegate;
import mockit.NonStrictExpectations;
import org.junit.Before;
import org.junit.Test;
public class FooTest
{
FooSubClass fooSubClass;
#Capturing Foo fooMocked;
#Before
public void setUp()
{
fooSubClass = new FooSubClass();
}
#Test
public void testAMethod()
{
new NonStrictExpectations()
{
{
fooMocked.setBaz(anyString);
result = new Delegate()
{
void setBaz(String baz)
{
Deencapsulation.setField(fooSubClass, "bazField", baz);
}
};
times = 1;
fooMocked.getProcessedBaz();
result = new Delegate()
{
String getProcessedBaz()
{
return "PROCESSED_" + Deencapsulation.getField(fooSubClass, "bazField");
}
};
times = 1;
}
};
fooSubClass.setBaz("abc");
System.out.println(fooSubClass.getProcessedBaz());
}
}
NOTE: This was inspired by Varun's answer, but I wanted to avoid using reflection and intermediate classes. Rogério also provided a viable alternative, but it did not fit into the overall structure of my test. Thanks to both!
Here's how I finally got it working:
public interface Foo {
void setBaz(String baz);
String getProcessedBaz();
}
#RunWith(JMockit.class)
public class FooTest {
#Injectable
private Foo mockedFoo = null;
#Test
public void testBaz() {
new Expectations() {
private String bazState; // Variable inside Expectations stores the state between calls
{
mockedFoo.setBaz(anyString);
result = new Delegate() {
void setBaz(String baz) { bazState = baz; }
};
mockedFoo.getProcessedBaz();
result = new Delegate() {
String getProcessedBaz() { return "PROCESSED_" + bazState; }
};
}
};
mockedFoo.setBaz("ABC");
assertEquals("PROCESSED_ABC", mockedFoo.getProcessedBaz());
}
}
One way to write such an state-based test is:
public interface Foo {
void setBaz(String baz);
String getProcessedBaz();
void someOtherMethod();
}
public static class ClassUnderTest {
String doSomething(Foo foo) {
foo.setBaz("ABC");
foo.someOtherMethod();
return foo.getProcessedBaz();
}
}
#Test
public void mockFoo() {
Foo foo = new MockUp<Foo>() {
String baz;
#Mock void setBaz(String baz) { this.baz = baz; }
#Mock String getProcessedBaz() { return "PROCESSED_" + baz; }
}.getMockInstance();
String res = new ClassUnderTest().doSomething(foo);
assertEquals("PROCESSED_ABC", res);
}
An equivalent test can also be written with the JMockit Expectations API (using Delegate objects), but it would be more verbose as that API is meant for behavior-based testing (ie, when you care more about which methods get invoked than state-transfer between objects).

Setting up a test system with "real data"

So right now I'm using JUnit 4 and in the #BeforeClass methods I setup everything needed to reset the user schema or to prepare sample data.
Now, it's not that I don't like this approach but I found it quite frustrating for the following reason:
I'm using the Parameterized annotation to run the very same tests with different input data. Parameterized doesn't work on #BeforeClass because #BeforeClass works with a static method.
This means I have to replicate tests if I want to keep the #BeforeClass logic. I can't use #After and #Before because those will happen after every test and it would be an overhead.
I was thinking I could refactor this Unit Tests in the sense that I'll write an abstract class that handles the test and a subclass for every group parameters I want to try so that I can have the test code written only once.
I'm hoping you can suggest a cleaner option with the following starting point: the use of #Parameterized, the need to run the "database" method only once per parameter group.
EDIT:
this is an example of my class without the BeforeClass
RunWith(LabelledParameterized.class)
public class TestCreateCampaign extends AbstractTestSubscriberCampaign {
public TestCreateCampaign(String label, String apiKey, String userKey,
int customerId) {
super(label, apiKey, userKey, customerId);
}
#Before
public void setUp() throws Exception {
super.setUp();
}
#After
public void tearDown() throws Exception {
super.tearDown();
}
#Parameters
public static Collection<Object[]> generatedData() {
return DataProvider.generatedCorrectSubscriberData();
}
#Test
public void testCreateEmailCampaignBothTriggered() {
// TEST
}
#Test
public void testCreateTextCampaignTriggered() {
// TEST
}
#Test
public void testCreateTextCampaignTest() {
// TEST
}
// Other Tests
}
This depends on how you want to set up your classes, but you can use a ClassRule for this. This does the same job as a TestRule, but it runs once for each class, rather than each test. This can be combined with Parameterized and TestRule, such as:
#RunWith(Parameterized.class)
public class TestCreateCampaign {
#ClassRule
public static ExternalResource beforeAfterClass = new ExternalResource() {
#Override
protected void before() throws Throwable {
System.out.println("before each class");
}
#Override
protected void after() {
System.out.println("after each class");
}
};
#Rule
public ExternalResource beforeAfter = new ExternalResource() {
#Override
protected void before() throws Throwable {
System.out.println("before each test");
}
#Override
protected void after() {
System.out.println("after each test");
}
};
#Parameters(name = "{index}: fib({0})={1}")
public static Iterable<Object[]> data() {
return Arrays.asList(new Object[][] { { 3, 0 }, { 4, 1 } });
}
private int fInput;
private int fExpected;
public TestCreateCampaign(int input, int expected) {
fInput = input;
fExpected = expected;
}
#Test
public void test1() {
System.out.println("test1 fInput=" + fInput);
}
}
This produces the following output:
before each class
before each test
test1 3
after each test
before each test
test1 4
after each test
after each class
This seems to be what you're looking for. To cut down on the amount of duplication, you can of course define beforeAfterClass and beforeAfter in a separate java class.
These are available in JUnit 4.9+.
What about calling your setup method from the constructor of your parameterized test class?
Edit:
OK, do I don't know of anything that does this automatically, but I think you could code up a Rule to do it. You could either implement a Rule from scratch of extend ExternalResource. Here is what I think it would do.
The constructor would take an instance of the test class and an ExternalResource instance.
In the constructor it would find the list of methods that contain the #Test annotation a get a count. It would set an iteration count to 0.
In the before method it would increment the iteration count and if it is 1 after increment (or 0 before) it would invoke the before method on the passed ExternalResource.
In the after method it would check to see if the iteration count was equal to the number of tests and if so call the after method on the passed ExternalResource.
You might need to use a different callback class / interface and ExternalResource since the before and after methods are protected. If you really wanted to be cool, you would define your own BeforeParameters and AfterParameter annotations in your rule and it would look for those methods in the passed instance.
If you develop this please post it or submit it to JUnit for inclusion.
Here is what I came up with, not as nice as I would like:
#RunWith(Parameterized.class)
public class TestExample {
private interface BeforeAfter {
void before();
void after();
}
public static class Resource extends ExternalResource {
private final int count;
private final BeforeAfter ba;
private int iteration = 0;
Resource(Object instance, BeforeAfter ba) {
int localCount = 0;
for (Method method : instance.getClass().getMethods()) {
if (method.getAnnotation(Test.class) != null) {
localCount++;
}
}
this.count = localCount;
this.ba = ba;
}
#Override
protected void before() throws Throwable {
if (iteration == 0) {
ba.before();
}
iteration++;
}
#Override
protected void after() {
if (iteration == count) {
ba.after();
iteration = 0;
}
}
}
#Parameters
public static Iterable<Object[]> data() {
return Arrays.asList(new Object[][] { { 3, 0 }, { 4, 1 } });
}
#Rule
public static Resource resource = new Resource(new TestExample(0, 0), new BeforeAfter() {
#Override
public void before() {
System.out.println("setup");
}
#Override
public void after() {
System.out.println("cleanup");
}
});
private int fInput;
private int fExpected;
public TestExample(int input, int expected) {
// System.out.println("Constructor invoked" + fInput);
fInput = input;
fExpected = expected;
}
#Test
public void test1() {
System.out.println("test1 fInput=" + fInput);
}
#Test
public void test2() {
System.out.println("test2 fInput=" + fInput);
}
}
Resulted in:
setup
test1 fInput=3
test2 fInput=3
cleanup
setup
test1 fInput=4
test2 fInput=4
cleanup
See How to load DBUnit test data once per case with Spring Test for a way of initialising your test data only once per test run.

Running two same tests with different arguments

I have a test with 15-20 different test cases, I want to run the same test with twice with two different parameters which are supposed to be passed to the test's BeforeClass method, for instance:
public class TestOne {
private static ClassToTest classToTest;
#BeforeClass
public static void setUp() throws Exception {
classToTest = new ClassToTest("Argument1", "Argument2");
}
#Test
public void testOne() {
........roughly 15 - 20 tests here
}
public class TestTwo {
private static ClassToTest classToTest;
#BeforeClass
public static void setUp() throws Exception {
classToTest = new ClassToTest("Argument3", "Argument4");
}
#Test
public void testOne() {
........roughly 15 - 20 tests here, same as in TestOne
}
As you can see the only difference between these two tests is in the setup method, which passes different values to the constructor of the ClassToTest. I don't want to replicate the test methods in both classes, but would prefer either inheritance or some other intelligent way to achieve this in one class.
This seems like a perfect use case for JUnit4's #Parameters; see https://blogs.oracle.com/jacobc/entry/parameterized_unit_tests_with_junit or http://www.mkyong.com/unittest/junit-4-tutorial-6-parameterized-test/ . That said, you'll have to move the initialization from the setUp method to a constructor for the test class.
For what it's worth, here is how you would do it with TestNG:
public class TestFactory {
#Factory
public Object[] createTests() {
return new Object[] {
new ClassToTest("arg1", "arg2"),
new ClassToTest("arg3", "arg4")
};
}
}
public class ClassToTest {
public ClassToTest(String arg1, String arg2) {
this.arg1 = arg1;
this.arg2 = arg2;
}
#Test
public void testOne() {
// use arg1 and arg2
}
}
Thanks all for your quick replies. This is how I did it finally
public abstract class Base {
final HeavyObject heavy;
protected Base(HeavyObject heavy) {
this.param = param;
}
#Test
public void test() {
param.doSomething();
}
#Test
.............More tests here
}
public class FirstTest extends Base{
private static HeavyObject param;
#BeforeClass
public static void init() {
param = new HeavyObject("arg1", "arg2");
}
public FirstTest() {
super(param);
}
}
public class SecondTest extends Base{
private static HeavyObject param;
#BeforeClass
public static void init() {
param = new HeavyObject("arg3", "arg4");
}
public FirstTest() {
super(param);
}
}
Base is an abstract class which has all the tests and FirstTest and SecondTest create their own objects with different parameters and pass it to the abstract class to use it.
As per the documentation (http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html):
A subclass does not inherit the private members of its parent class.
However, if the superclass has public or protected methods for
accessing its private fields, these can also be used by the subclass.
How about this:
public class TestOne {
private static ClassToTest classToTest1, classToTest2;
#BeforeClass
public static void setUp() throws Exception {
classToTest1 = new ClassToTest("Argument1", "Argument2");
classToTest2 = new ClassToTest("Argument3", "Argument4");
}
#Test
public void testOne() {
testOneImpl(classToTest1);
testOneImpl(classToTest2);
}
public void testOneImpl(ClassToTest classToTest) {
// exact samew as whatever your current testOne() test method is
}
....
}
EDIT:
Or to keep method count down:
public class TestOne {
private static List<ClassToTest> classesToTest;
#BeforeClass
public static void setUp() throws Exception {
classesToTest = new ArrayList<>;
classesToTest.add( new ClassToTest("Argument1", "Argument2"));
classesToTest.add( new ClassToTest("Argument3", "Argument4"));
}
#Test
public void testOne() {
for (ClassToTest classToTest: classesToTest) {
... same test content as before
}
}

Categories

Resources