Should we avoid usage of Powermock? [closed] - java

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 3 years ago.
Improve this question
In general, Powermock allows us to mock/stub an static behavior or state. For example, we could mock an static method of utility class like public static String buildKeyFrom(...) {...} and override its behavior. Or even return our mock instance when target class tries to create an object using constructor of class new MyService(...)
Few examples of powermock API usage:
when(StorageKeyUtils.buildKey(id, group, suffixes)).thenReturn("my:group-test:an-id:suffix1")
whenNew(MyParser.class).withArguments(factory).thenReturn(parserMock)
And... it works, actually it helps to avoid refactoring to improve test-ability of our code. You have no more needs to extract static behavior into separate classes, no needs to introduce factories to instantiate new objects and so on.
But, Powermock also have disadvantages:
Complicated setup.
In fact, it's not just single whenSomething like in Mockito, besides this and replacement of test-runner, you also forced to use #PrepareForTest and PowerMock.mockStatic(..). Try to remember what classes to be described within the annotation and inside mockStatic, without checking of tests you implemented previously or documentation.
Sometimes it even works without mockStatic while you still trying to mock static methods.
Of course we could spend some time and investigate documentation to clarify all questions...
Bugs and glitches.
Sometimes it works, sometimes it doesn't. Examples:
Conflicts with coverage tools. Due conflicts with instrumenting of classes you may face loss of coverage of your code by test, for example - JaCoCo
Try to google for powermock mbeanserver... Why powermockito tries to abuse mbeanserver and forces us to mark our test-sets with #PowerMockIgnore? Since 2013. Bot sometimes it works OK without exclude, why? - idk
Unable to mock static method or constructor passed as lambda by reference, for example: ``
It simply encourages usage of static - ambassadors of OOP welcome to describe why we mustn't use static methods, etc
In general, I would say yes, we should avoid usage of Powermock. One doubtful case I see for it - you have no time for appropriate design of you code to make it testable enough without power-mockito (, but do you really need that quality of testing, if you don't have time for code-design?)
What do you think? Do you use Powermock on regular basis? Do you follow some rules while using Powermock on your project?

Typically, clean code won't need powermock for testing. Because clean code supports dependency injection, is loosely coupled and is easy to unit test so doesn't rely on static methods.
Legacy / dirty code on the other hand is riddled with static methods, is tightly coupled and doesn't support dependency injection. It's these legacy code bases where you'll need powermock for testing

I don't recommend PowerMock but life is not always as we would like to have, sometimes you come into project which, let's say, doesn't follow best programming practices, then PowerMock can be accepted in my opinion. Question is a bit too broad.

Related

Should pure java methods be static? [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 3 years ago.
Improve this question
Lets say we have a pure java method. Its a simple validation method. It validates if the input is correct, and throws an exception if not.
static void validateInputIsOk(String input) throws InvalidArgumentException {
if (input == null || !input.equals("Valid input")) {
throw new InvalidArgumentException(new String[]{"Bad input"});
}
}
Its pure, and its static, its small, and easy to reason about.
So i`ve been reading a lot about java static methods and a lot of people advises against this.
Mainly due to testability.
Now that part i fully get. Its not easy mocking a static method. If I use this validator inside some other unit, then I must either accept it will be a part of the test (which could be ok since its pure), or use some sort of static mock framework.
But in order to make it mockable, and non static, I would have to sacrifice the simplicity and readability of my code. I would have to deal with creating the object, and possibly passing it as a parameter to the unit using it.
So in this light I would favour making my pure methods static, and not bother mocking them. It seems the to keep my code most simple and clean.
Would you think im right? Is it something im missing here?
I would argue that you only should mock methods that are public. I would also argue, that you only should test methods that are public. If your tests get too big this way, you should consider splitting up your implementation into more public classes, not necessarily make them non static.
Methods that have no side-effects, the term is functions, should be static. And are good style. Math offers many such functions.
For testing, one would not mock these functions, but test them in isolation.

java field qualifier best practice [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 7 years ago.
Improve this question
It is a good practice to use a proper qualifier between private, protected, private or default. But is there any other reason like performance or JVM optimization drawback default is used instead of private? As an example
public class Class1{
Class2 class2;
}
And where variable class2 could have been private.
Also if the variable is autowired or injected by DI framework. Framework calls field.setAccessible(true). Does that make any difference as per the performance or optimization.
I think I now understand the motivation for this question.
The reasons for using the correct access modifiers on variables in normal Java are well understood. Basically, it is all about modularity, encapsulation, avoiding unwanted / harmful coupling and so on.
What about Spring?
Well it is true that Spring can circumvent normal access rules and allow you to inject private variables. However, from what I understand, you have to deliberately annotate your private fields with #autowire or similar for this to occur. What is actually going on here is that Spring is following an "instruction" that is explicitly declared in the source code by means of the annotation. Spring XML-based wiring won't let you inject a value into a private field or using a private setter.
In the light of this, the argument that Spring allows you break private encapsulation is ... while technically true ... ultimately self-serving. Sure, you can do it. But you have to do it explicitly, deliberately ... by design. And it ONLY happens when the objects are wired.
By contrast, if you are sloppy about the modifiers, and declare every instance variable as public or package private, then you are leaving open the possibility of all sorts of lazy, ill-considered, or even accidental breaking of encapsulation. And even if you (the original author) are disciplined, the next guy reading / maintaining your code can't be sure that you have been disciplined. He has to check ...
So how do you "force" someone to toe the line?
It is probably best to persuade rather than force, but the way to force people to write decent code is to get your project manager / quality manager to adopt a coding standard, and insist that it is followed. (But this can be easier said than done if your management doesn't understand the long-term costs of poor quality.)
The real reason we have these pesky coding standards is so that the code can be maintained ... by someone other than the guy who wrote it. A good IT manager will understand this. A good PM will understand this. A good programmer will understand this.
If it's not meant to be used by any other application - then just make it private. The point is OTHER developers can't read your mind. And if it's not private, then they will think, that it is meant to be used outside of class.

Alternatives to Assert [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 8 years ago.
Improve this question
The reasons I am dissatisfied with assert keyword in Java are
1) it's disabled by default, so it is a headache to make sure it's enabled when I want it to be
2) its behavior is rather rigid (I would want some inversion of control, ideally); but that's not terribly important.
Some of the alternatives I can think about:
JUnit's assertEquals() and such - good for tests, but can't use in main code
Guava's preconditions - great, but no assertion methods per se.
My own assertion library - I wrote it back in 1999, and back at the time it was great, but now I want to standardize.
Anything else?
So.. to sum it up.. how do I assert in production code in a way that is not disabled by default?
(And yes, this may be considered an anti-pattern by some, but I do want at least some assertions in Production, even if assertion failures are just silently logged. I see some room for that even in shrink-wraps, and definitely in websites).
I'd use Spring's Assert class, it includes a fairly extensive range of checks.
I am not sure if this is what you want, but I'm routinely using commons-lang Validate for many years already. Usually in public API methods/constructors to ensure that arguments are passed correctly. Not just notNull (see Lombok's #NotNull for this) but also noNullElements etc.
I especially like the <T> T notNull(T object) signature for immutables:
private final JSCodeModel codeModel;
private final String name;
public FunctionDeclarationImpl(JSCodeModel codeModel, String name,
String[] parameterNames, JSSourceElement[] sourceElements) {
this.codeModel = Validate.notNull(codeModel);
this.name = Validate.notNull(name);
...
}
What are your requirements, actually?
JUnit's assertEquals() and such - good for tests, but can't use in main code
Nothing technically prevents you from using JUnit assetions (and/or Hamcrest matchers) in your main code. Just include the Junit jar in your classpath. It's usually not done but that's more of a convention than any technical limitation.
Java 7 also introduced Objects.requireNotNull(obj, message) and similar methods although not as full featured as JUnit assertions.
but I think if you want to go with a more standardized approach Guava's preconditions is probably best.

Why did Java make package access default? [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
I'm asking this question because I believe they did it for a very good reason and that most people do not use it properly, well from my experience in industry so far anyway. But if my theory is true then I'm not sure why they included the private access modifier...?
I believe that if default access is properly used it provides enhanced testability whilst maintaining encapsulation. And it also renders the private access modifier redundant.
The default access modifier can be used to provide the same affect by using a unique package for methods that need to be hidden from the rest of the world, and it does this without compromising testability, as packages in a test folder, with the same are able to access all the default methods declared in a source folder.
I believe this is why Java uses package access as 'default'. But I'm not sure why they also included private access, I'm sure there is a valid use case...
I agree about using the default (package private) modifier for stuff that is to be accessed by tests, but I don't agree about private being unnecessary. Even for tests there is a lot of stuff that is not needed to be visible.
For a good test, implementation details are unnecessary and should not be visible outside the class. The more "whitebox" a test is, the more fragile it is. I usually limit the default modifier to fields I expect to be set via dependency injection and set manually in a test. (I could also use constructor injection and get rid of this, but this is more convenient.)
I propose little thought-experiment. Consider this code:
public void promoteUser(User user)
{
int newRank = computeNew(user);
user.setRank(newRank);
}
private int computeNewRank(User user)
{
return user.getRank() + 1;
}
One might feel computeNewRank should be tested (real implementation might do lot more stuff). But let's forget that for a moment and through the magic of inlining do this:
public void promoteUser(User user)
{
int newRank = user.getRank() + 1;
user.setRank(newRank);
}
The beauty of this experiment is that it applies to private methods of any size. You can always imagine yourself inlining private member and asking yourself "What do I really want to test here?". Is it the private method itself or perhaps new class/component with brand new functionality that's disguised as private method? The point is, you should rarely (if ever!) need to test private (or even package/internal) members. To outside world, to your contract consumers those are all irrelevant details.
Now, of course we could replace everything with system tests. But then how your regular work flow would look like? What if in order to test the rank promotion code you'd have to log user, register for session, wait 3 minutes, enter promotional code, receive sms, confirm... You see my point.
It's good to remember that unit tests are for you, not the other way around. You can bend them, adjust them, make them fit so that you can deliver software of better quality. Thier purpose is not to help you achieve some magical goal of 100% coverage, but rather to give you immediate feedback on what you're doing so that you can react more quickly to bugs and failures you will encounter. Or in other words, to improve your productivity.

Naming convention JUnit suffix or prefix Test [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 5 years ago.
Improve this question
Class under test MyClass.java
JUnit test case name alternatives:
TestMyClass.java
MyClassTest.java
http://moreunit.sourceforge.net seems to use "Test" as prefix default but I have seen both uses. Both seems to be recognized when running the entire project as unit test in eclipse as it is the annotation inside classes that are parsed for #Test. I guess maven does the same thing.
Which is preferred?
Another argument for suffix - at least in english language:
A class usually represents a noun, it is a model of a concept. An instance of one of your tests would be a 'MyClass test'. In contrast, a method would model some kind of action, like 'test [the] calculate [method]'.
Because of this, I'd always use the 'suffix' for test classes and the prefix for test methods:
the MyClass test --> MyClassTest
test the calculate method --> testCalculate()
I prefer to use the suffix - it means that looking down the list of files in a directory is simpler: you don't have to mentally ignore the first four letters to get to something meaningful. (I'm assuming you have the tests in a different directory to the production code already.)
It also means that when you use Open Type (Ctrl-T) in Eclipse, you end up seeing both the production code and its test at the same time... which is also a reminder if you don't see a test class :)
Prior to JUnit 4 it was common to name your test classes SomethingTest and then run JUnit across all classes matching *Test.java. These days annotation driven JUnit 4, you just need to annotate your test methods with #Test and be done with it. Your test classes are probably going to be under a different directory structure than your actual source (source in src/ test classes in test/) so these days prefixes/suffixes are largely irrelevant.
Not to offend anybody, but I think it is fair to say that "moreunit" is much less known than JUnit, which is pretty much ubiquitous, and established the convention of suffixing test classes "Test".
Although JUnit4 did away with the necessity of following both class and method naming conventions (resp. "postfix Test" and "prefix test"), I think both are still useful for clarity.
Imagine the horror of having src/test/java/.../MyClass.myMethod() tested by src/main/java/.../MyClass.myMethod()...
Sometimes, it is useful to diverge from the JUnit3 conventions - I find that naming setup methods after what they do ("createTestFactory()") and annotating them "#Before" is much clearer than the generic "setUp()".
This is particularly useful when several unrelated setup actions need to be performed - they can be in separate methods, each tagged #Before. This communicates the independence of the actions very nicely.
I prefer using the TestClassName syntax. When using the other syntax I have trouble identifying which is the test and which is the actual class in editors when I have both open. Having to look for the Last four letters in the name is tiresome and also these letters are not always displayed.
For me the other syntax leads to several wrong swapping´s between files every day and that is time consuming.
I think it is important you feel comfortable with your tests if you are working alone. But if you're in a group, you better sit down and get something fixed. I personally tend to use suffix for classes and prefix for methods and try to have my groups adapt to this convention.
I also use MyClassTest_XXX when I want to split my test into multiple classes. This is useful when testing a big class and I want the tests logically grouped. (Can't control legacy code so this scenario does come up.) Then I have something like KitchenSinkTest_ForArray, KitchSinkTest_ForCollection, etc.
I suggest MyClassTests.
Classes should be noun phrases, so commonly used MyClassTest and less common MyClassTests or MyClassTestCase or MyClassTestFixture all work. Technically, an instance of a JUnit test class represents a test fixture, but TestFixture is a bit too verbose for me.
I think that MyClassTests conveys intent in the best way because there are typically multiple test methods in a class each representing a single test (test case).
i prefer the suffix: TestCase. this is consistant with: http://xunitpatterns.com/Testcase%20Class.html

Categories