How to check a method executed in the unit test context? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am trying to add some features to the legacy libraries and plan to make it testable.
I want to limit some methods allowed call in the testing context, like change the global system configurations. Because some changes are dangerous for production, to limit the accessablitiy is important.
I use the junit4 to test my project, any suggestions for it?
class Foo {
public void methodA() {
// is it possible limit methodA only allowed invoked by JUNIT ?
}
}

I would make a stub
Lib l = new Lib() {
#Override
void xxx() {
Assert.fail("calling xxx() is not allowed");
}
};

The thing comes in my mind is to use dependency injection to use two different implementations of the same interface, one for production and one for testing. The one you inject in the production execution could just have empty method that doesn't actually do nothing. Concept:
class Foo {
private Bar bar;
public Foo() {
bar = new DefultBarImplementation();
}
public setBar(Bar bar) {
this.bar = bar;
}
//use bar in your other methods
}
In your tests
Foo foo = new Foo();
foo.setBar(new TestBarImplementation());

You can make the methods package-private and have the tests in the same package.
public class Foo{
public void publicMethod();
void forTestingOnly();
}

Related

Call super make must be first statement in method [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
If inherited method does not contain a call to super in first statement, I need a compile error, requires constructor-like behavior. Is it possible to do this?
public class ModelBase {
protected int defaultCount;
public void init() {
defaultCount = 10;
}
}
public class Model extends ModelBase {
#Override
public void init() {
System.out.println(defaultCount);
super.init();//need error or notification
}
}
Note that requiring a call to super at all is considered an anti-pattern, in part because there is no way to enforce it, or to enforce that it is called at the right point in the method etc.
One way to do this with plain Java is not to require a call to super at all, but rather to provide a non-overrideable method which calls a subclass-specific method at the right time.
For example:
class YourClass {
final void yourMethod() {
// Stuff you want to happen first.
// and then at the end, call
subclassSpecific();
}
protected void subclassSpecific() {}
}
Now, subclasses can override that method to provide specific behavior that will occur after the rest of the things in yourMethod:
class YourSubclass extends YourClass {
#Override protected void subclassSpecific() {
// Whatever.
}
}

How to create a function that cannot be executed by a constructor? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Say I have function x which is a function in an abstract class. x adds itself to a private arraylist if it does not already contain it. I want to make a function that cannot be executed inside the constructor so that 'x' cannot be added to the arraylist if the constructor errors, and can only be called after the constructor(s) has finished. The gist of my situation is that I want the set to be private so only the class A can access it, nothing should ever be removed from the list if it is added, the addToArray function should only ever need to happen once and should never happen from the constructor. The constructor would only matter if it is a subclass' constructor.
public abstract class A {
public A () {
//do stuff :)
}
public abstract void doStuff();
public final void addToArray() {
if(isCalledFromConstructor/*HELP ME HERE*/)
throw new RuntimeException("Cannot execute addToArray function from a constructor");
if(!AS.contains(this))AS.add(this);
}
private static final java.util.Set<A> AS = new java.util.concurrent.ConcurrentSkipListSet<A>();
public static final class B extends A {
public B(){
addToArray();//THROW AN ERROR HERE
}
#Override
public void doStuff(){
System.out.println("Doing stuff");
}
}
}
With more context on what you’re trying to accomplish, I might be able to give a better suggestion on achieving your ultimate goal. That said, if you are absolutely set on doing what you are asking, one way is to call
Thread.currentThread().getStackTrace()
from within addToArray and examine the contents of the stack trace to see if you’re currently inside of a constructor.
In particular this
boolean isCalledFromConstructor() {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
for (StackTraceElement stackTraceElement : stackTrace) {
String methodName = stackTraceElement.getMethodName();
if (methodName.equals("<init>")) return true;
}
return false;
}
should do it for you, although it's not my favorite bit of code :)
As other people have commented, doing this may be a sign of a design oversight. Please give more details on the big picture goal if you can.
You could have a private variable like boolean isInitialized and set this to true in constructor. In the add method check if this value is false and throw error.
If your environment allows it you could use #PostConstruct method annotation to add it to your list safely.
But i also recommend to check your code design. You are adding an instance to a private static list that is not thread safe.

Getting my head around implementations [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have an interfaceFileService
And an implementation of it FileServiceBean
I want to be able to process multiple filetypes.
e.g. fileService.processFile(FileDescriptor);
Where, the fileDescriptor is a class e.g.
public class FileDescriptor {
#Column(name = "FILE_TYPE")
protected String fileType;
}
Then I want multiple extensions of the FileServiceBean to process different filetypes. And FileServiceBean would have all the methods common to all filetypes.
e.g.
PhotoProcessingBean extends FileProcessingBean
VideoProcessingBean extends FileProcesingBean
How do I make the interface decide what implementation to use? I am rather new to this and not really quite sure how to ask the question to search google for the answer.
Ideally it would not just accept FileDescriptor. e.g. It could be something else like just File.
fileService.processFile(Object);
Well, in the end you have to put the decision logic somewhere, the only question is where?
I think this is a classic application of the factory-pattern: you create an object (the "factory") which has the sole purpose of deciding which concrete implemenation of a common interface to create for a given case. See https://en.wikipedia.org/wiki/Factory_method_pattern
Along the lines of:
PhotoProcessingBean extends FileProcessingBean {...}
VideoProcessingBean extends FileProcesingBean {...}
class FileProcessingFactory {
public static FileService createFileService(FileDescriptor descriptor) {
switch(descriptor.getFileType()) {
case 'Photo': return new PhotoProcessingBean();
case 'Video': return new VideoProcessingBean();
default: // do some error handling
}
}
}
And using it:
for(FileDescriptor descriptor : /* wherever they come from */) {
FileService processor = FileProcessingFactory.createFileService(descriptor);
processor.processFile(descriptor);
}
Sure enough you can also soften up the interface by accepting objects instead of file descriptors. This depends on the concrete application.
Assuming you have an interface:
public interface IFileService{
void processFile();
}
And the FileProcessingBean class that implements this:
public class FileProcessingBean implements IFileService{
//other code here
#Override
public void processFile(){
//add code for implementation of method
}
}
If you have two other classes that extend FileProcessingBean:
public class PhotoProcessingBean extends FileProcessingBean{
#Override
public void processFile(){
System.out.println("Processing PHOTO...");
}
}
public class VideoProcessingBean extends FileProcessingBean{
#Override
public void processFile(){
System.out.println("Processing VIDEO...");
}
}
If you would like to use it:
//This is an OOP concept called Polymorphism:
IFileService photoProcess = new PhotoProcessingBean();
IFileService videoProcess = new VideoProcessingBean();
Calling photoProcess.processFile(); and videoProcess.processFile() would yield different the implementations:
photoProcess.processFile();
videoProcess.processFile();
And you'll get the following output:
Processing PHOTO...
Processing VIDEO...
Regarding your point about not just accepting FileDescriptor but also 'something else', my recommendation would be to either know exactly what sort of arguments you are expecting, and then either implementing overriding methods or via an interface. It would not be wise to use Object as a method argument as Object is a superclass from which all objects are descendants of. You would essentially be opening the 'floodgates' and potentially run into runtime errors.

How do I use "getter" methods (for beginners)? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
When it comes to Java programming you'll stumble upon this along your way. Here is an elementary answer to help new programmer learn how to use a getter method without the terminology or complexity of people is this field.
By creating an accessor method (and not creating a mutator method).
public class MyClass {
public MyClass(int v) {
this.myField = v;
}
private int myField;
public int getMyField() {
return myField;
}
}
Then you can call that "getter" in some other class with an instance of MyClass.
public class SomeOtherClass {
public static void doSomething(MyClass my) {
System.out.println(my.getMyField());
}
public static void main(String[] args) {
doSomething(new MyClass(42)); // <-- for example.
}
}
When working with Java projects you'll stubble upon "getter" methods or "get" methods. This is how I solved my problems, by following these instructions.
If you're confused on why you should use "getter" methods follow this link.
Note that this is for beginners and the language/format I use
may (and in some cases is) not be proper.
Note that you will also need to have a general concept of Java.
This is for people who don't understand some of the Java terminology
Take a look at my (example) project set up.
Package Explorer/Setup
Project Name
src
(default package/package name)
Class1.java
Class2.java
Class 1
public class Class1 {
// creates an object
static Class2 class2 = new Class2();
public static void main(String[] args) {
// this will print our method (method1) in our class (Class2)
System.out.println(class2.method1());
}
}
Class 2
public class Class2 {
// this is the method we are accessing
public double method1(){
// this is what we are returning (sending back)
return 2.5;
}
}
Output (console)
2.5
So how do we access a "getter" method?
If you haven't noticed already, we printed it in our class "Class1" using...
System.out.println(class2.method1());
we used class2. because we created an object that allows us to access our Class2. Notice that class2 is lowercase and Class2 is uppercase, this is because class2 (lowercase) is the object we've created. Thus we are using the object to use our "getter" method not our class. We create our object using...
static Class2 class2 = new Class2();

Is it good practice in Java for a class's method to redundantly return a modified global field of the class? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Is it good practice in Java for a class's method to redundantly return a modified global field of that class?
Note: I edited the examples below to correct my code.
For example:
public class MyClass {
private String veryImportantString;
public static void main(String [] args) {
MyClass myObject = new MyClass();
myObject.fieldQuestion();
}
public void fieldQuestion() {
veryImportantString = "Hello, StackOverflow";
String newString = addStringToVeryImportantString(" World!");
System.out.println(newString);
}
public String addStringToVeryImportantString(String inputStr) {
this.veryImportantString = veryImportantString + inputStr;
return veryImportantString;
}
}
In the above example, addStringToVeryImportantString is returning veryImportantString, even though as a class field it has been modified and is globally available to the calling method.
In the below example, I do the same thing without returning the field:
public class MyClass {
private String veryImportantString;
public static void main(String [] args) {
MyClass myObject = new MyClass();
myObject.fieldQuestion();
}
public void fieldQuestion() {
veryImportantString = "Hello, StackOverflow";
addStringToVeryImportantString(" World!");
String newString = veryImportantString;
System.out.println(newString);
}
public void addStringToVeryImportantString(String inputStr) {
this.veryImportantString = veryImportantString + inputStr;
}
}
My question is: does it matter? Is there any difference in terms of coding standards, readability, efficiency, etc.? In a way, it makes sense to never return a global class field that a function has modified, because what is the point? The field is available anyway. On the other hand, maybe it makes sense to return the field in order to indicate that the primary purpose of the function is to modify that field and return the value.
Thanks for your input.
It is a usual coding standard for a method to either mutate an object (or variable) or get information about it but never both. Therefore a method that has a return will be assumed at first glance not to have any secondary effects (like changing veryImportantString). This is not a hard and fast rule and there are many reasons to break it but it should never be broken lightly.
Secondly the method signature in the second snippet (with a void return) could only reasonably do one thing; change veryImportantString. But with a return it could do two things; change veryImportantString and return it or return a seperate string based upon veryImportantString. As the void signature is less ambiguous it is preferable (unless theres a specific reason to do otherwise)
For your example, its not particularly important.
In general when you have a private piece of data and a public method. Your only way to get information out to the user of an instance of your class related to the private data is via returning something from a public method. Remember that most Java programs are much more complex and the need to return data related to a private field (java beans for instance) are much more common.

Categories