Is it bad to set up singletons such that all methods are static methods? - static

I frequently setup singleton classes that are intended to be used by other programmers and I find that I'm not sure if there is a preferred way to setup access to methods in those classes. The two ways I've thought to do it are:
public class MyClass {
private static MyClass instance;
public static void DoStuff( ) {
instance.DoStuffInstance( );
}
private void DoStuffInstance( ) {
// Stuff happens here...
}
}
where the usage is: MyClass.DoStuff( );
or something more like this:
public class MyClass {
public static MyClass instance;
public void DoStuff( ) {
// Stuff happens here...
}
}
where the usage is: MyClass.instance.DoStuff( );
Personally, I tend to prefer the first option. I find that having MyClass.instance all over the place is both ugly and unintuitive to remember for less experienced programmers.
Is there any good reason to prefer one of these over the other? Opinions are fine. Just curious what others think.

I've never seen a Singleton implemented this way. A typical setup might be something like this:
public class MyClass {
private static final MyClass instance = null;
// Private to ensure that no other instances can be allocated.
private MyClass() {}
// Not thread safe!
public static MyClass getInstance() {
if( instance == null ) {
instance = new MyClass();
}
return instance;
}
public void DoStuff( ) {
// Stuff happens here...
}
}
This way all of the calls will be similar to instance.DoStuff(); and you will only need to define one method per "operation", rather than needing a static method and then the actual "instance" method that your first approach uses.
Also, the way you have it set up, it looks like you can call those static methods before the instance is actually initialized, which is a problem.

Related

How to skip invoking another method to create a mock object?

I have a class of methods, if I want to test one method, but the objects created in this method depend on other methods in the class. I don't want to actually call the other methods, I just want to create mock objects to test. How should I do it?
#Test
public void testLoadException(String id) {
WorkflowExecution mockWorkflowExection = getWorkflowExecution(id);
}
I tried to just do so
WorkflowExecution mockExecution = EasyMock.create(WorkflowExecution.class);
Easy.expect(this.test.getWorkflowExecution(EasyMock.anyString())).andReturn(mockExecution);
But this does not work, the test gives me Nullpointer exception.
So can I skip the calling of getWorkflowExecution(id), Thanks!
You need a partial mock. Your example doesn't make much sense. So here is what you seem to want.
public class WorkflowExecution {
public void theRealMethodIWantToCall() {
theMethodIWantToMock();
}
void theMethodIWantToMock() {
}
}
#Test
public void testLoadException() {
WorkflowExecution execution = partialMockBuilder(WorkflowExecution.class)
.addMockedMethod("theMethodIWantToMock")
.mock();
execution.theMethodIWantToMock();
replay(execution);
execution.theRealMethodIWantToCall();
verify(execution);
}

How to define an array in hadoop partitioner

I am new in hadoop and mapreduce programming and don't know what should i do. I want to define an array of int in hadoop partitioner. i want to feel in this array in main function and use its content in partitioner. I have tried to use IntWritable and array of it but none of them didn't work . I tried to use IntArrayWritable but again it didn't work. I will be pleased if some one help me. Thank you so much
public static IntWritable h = new IntWritable[1];
public static void main(String[] args) throws Exception {
h[0] = new IntWritable(1);
}
public static class CaderPartitioner extends Partitioner <Text,IntWritable> {
#Override
public int getPartition(Text key, IntWritable value, int numReduceTasks) {
return h[0].get();
}
}
if you have limited number of values, you can do in the below way.
set the values on the configuration object like below in main method.
Configuration conf = new Configuration();
conf.setInt("key1", value1);
conf.setInt("key2", value2);
Then implement the Configurable interface for your Partitioner class and get the configuration object, then key/values from it inside your Partitioner
public class testPartitioner extends Partitioner<Text, IntWritable> implements Configurable{
Configuration config = null;
#Override
public int getPartition(Text arg0, IntWritable arg1, int arg2) {
//get your values based on the keys in the partitioner
int value = getConf().getInt("key");
//do stuff on value
return 0;
}
#Override
public Configuration getConf() {
// TODO Auto-generated method stub
return this.config;
}
#Override
public void setConf(Configuration configuration) {
this.config = configuration;
}
}
supporting link
https://cornercases.wordpress.com/2011/05/06/an-example-configurable-partitioner/
note if you have huge number of values in a file then better to find a way to get cache files from job object in Partitioner
Here's a refactored version of the partitioner. The main changes are:
Removed the main() which isnt needed, initialization should be done in the constructor
Removed static from the class and member variables
public class CaderPartitioner extends Partitioner<Text,IntWritable> {
private IntWritable[] h;
public CaderPartitioner() {
h = new IntWritable[1];
h[0] = new IntWritable(1);
}
#Override
public int getPartition(Text key, IntWritable value, int numReduceTasks) {
return h[0].get();
}
}
Notes:
h doesn't need to be a Writable, unless you have additional logic not included in the question.
It isn't clear what the h[] is for, are you going to configure it? In which case the partitioner will probably need to implement Configurable so you can use a Configurable object to set the array up in some way.

what's the difference between object and primitive type when using matchers in EasyMock

//service to mock
public interface ServiceToMock {
public void operateDouble(Double dbValue);
public void operateCar(Car car);
}
//class under test
public class ClassUnderTest {
ServiceToMock service;
public void operateDouble(Double dbValue){
service.operateDouble(dbValue);
}
public void operateObject(Car car){
service.operateCar(car);
}
}
//unit test class
#RunWith(EasyMockRunner.class)
public class TestEasyMockMatcherUnderTest {
#TestSubject
private final ClassUnderTest easyMockMatcherUnderTest = new ClassUnderTest();
#Mock
private ServiceToMock mock;
#Test
public void testOperateCar() {
//record
mock.operateCar(EasyMock.anyObject(Car.class));
EasyMock.expectLastCall();
// replay
EasyMock.replay(mock);
//matcher here...
easyMockMatcherUnderTest.operateObject(EasyMock.anyObject(Car.class));
//easyMockMatcherUnderTest.operateObject(new Car());
// verify
EasyMock.verify(mock);
}
#Test
public void testOperateDouble() {
// record
mock.operateDouble(EasyMock.anyDouble());
EasyMock.expectLastCall();
// replay
EasyMock.replay(mock);
easyMockMatcherUnderTest.operateDouble(EasyMock.anyDouble());
// verify
EasyMock.verify(mock);
}
}
As the above code has shown, I intent to test two methods(operateDouble, operateObject). But things are kinda weird since everything runs fine in the operateDouble block while the compiler complaints an "Illegal state exception: 1 matchers expected, 2 recored." when runnig operateObject. And if commentting the method operateDouble out, the compaint goes away..So what is the difference between Double and my custom object Car, as the Double can also be considered as an object. And why does codes in operateObject runs well when commenting operateDouble method out?
EasyMock.anyDouble and EasyMock.anyObject are not meant to be used in replay mode. They are used to setup your expectations in record mode.
Use this in your first test (testOperateCar):
easyMockMatcherUnderTest.operateObject(new Car());
and something like this in your second (testOperateDouble):
easyMockMatcherUnderTest.operateDouble(1.0);
By the way, you don't need to call EasyMock.expectLastCall. It is only useful if you expect a void method to be called multiple times, for example:
mock.operateCar(EasyMock.anyObject(Car.class));
EasyMock.expectLastCall().times(3);

Autofixture, expected behavior?

Having a test similar to this:
public class myClass
{
public int speed100index = 0;
private List<int> values = new List<int> { 200 };
public int Speed100
{
get
{
return values[speed100index];
}
}
}
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var fixture = new Fixture();
var sut = fixture.Create<myClass>();
Assert.AreEqual(sut.Speed100, 200);
}
}
Would have expected this to work, but I can see why it's not. But how do I argue, that this is not a problem with AutoFixture, but a problem with the code?
AutoFixture is giving you feedback about the design of your class. The feedback is, you should follow a more object-oriented design for this class.
Protect your private state, to prevent your class from entering an inconsistent state.
You need to make the speed100index field, private, to ensure it remains consistent with the values List.
Here is what I see if I run debugger on your test:
Autofixture assigns a random number to speed100index field because it is public, and in your array there is nothing at point 53 (from my screenshot)
If you set speed100index to be private, Autofixture will not re-assign the number and your test will pass.

Easymock and Shiro

I am trying to use AbstractShiroTest abstract class for my unit tests as explained in http://shiro.apache.org/testing.html
I have my test class:
public class BeanTest extends AbstractShiroTest {
...
#Test
public void testShiro() {
Subject subjectUnderTest = createNiceMock(Subject.class);
expect(subjectUnderTest.isAuthenticated()).andReturn(true);
expect(subjectUnderTest.getPrincipal()).andReturn("cenap");
setSubject(subjectUnderTest);
assertTrue("Subject is not authenticated", SecurityUtils.getSubject().isAuthenticated());
assertNotNull("Subject principle null", SecurityUtils.getSubject().getPrincipal());
}
#AfterClass
public static void tearDownClass() {
tearDownShiro();
}
Both assertions fail... SecurityUtils.getSubject() returns some object but isAuthenticated() method of that object returns false and getPrincipal() method returns null. "expect" clauses do not seem to work. What am I missing?
Answering my own question as it might help someone. It was a stupid mistake...
The trick is: Do not forget adding
anyTimes();
after your expect statement and so not forget calling
replay (subjectUnderTest);
after that!
So your BeforeClass method should be like:
#BeforeClass
public static void setUpShiro() {
Subject subjectUnderTest = createNiceMock(Subject.class);
expect(subjectUnderTest.isAuthenticated()).andReturn(true).anyTimes();
expect(subjectUnderTest.getPrincipal()).andReturn(Admin).anyTimes();
setSubject(subjectUnderTest);
replay (subjectUnderTest);
}

Resources