PowerMockito: mock private method to throw private class - java

I've got a class that looks like this:
public class Foo {
public meth() {
try {
privMethod();
System.out.println("Yay!");
} catch (FooException e) {
System.out.println("Boo!");
}
}
private void privMethod() throws FooException {
//doOtherStuff
if (someCondition()) {
throw new FooException();
}
}
private class FooException extends Exception {
FooException(String message) { super(message); }
}
}
I want to write a unit test for this, using Mockito and Powermock. I know I can mock the private method like this:
Foo spy = PowerMockito.spy(new Foo())
PowerMockito.doNothing().when(spy, "privMethod");
But how do I tell it to throw the exception? I know it'll be something like this:
Powermockito.doThrow(/*what goes here?*/).when(spy, "privMethod");
What goes there?
Note that the exception is a private inner class, so I can't just do doThrow(new FooException()), since FooException isn't accessible from the unit test.

In general, you go.
Powermockito.doThrow(theThingToThrow)
goes there. Like doThrow(new RuntimeException("should be thrown")) for example. Or a more specific exception, depending what you want the code under test to do about the exception.
But of course: you want to instantiate a private class there. Which you can't do (easily, see here for terribly complicated ways to do that). From that point of view: you created a very-hard-to-test design. The answer is to rework that design, making it easier to test.
And a final word of warning: I think you should not need to use PowerMockito for this. Spies work with plain Mockito.
And when there is no hard need to use the PowerMock(ito) versions, then do not use them. Period. They have their place, but honestly: most often, needing PowerMock(ito) equals to "hard to test code".
Beyond that: looking at private methods translates to testing implementation details. And that is also something to avoid when possible.
So, in other words: A) it is close to impossible to test the above code in meaningful ways. B) It would also be bad practice to do so (as envisioned in the question). Therefore the "best" solution here is to step back and re-design the whole thing. Yes, I am serious.

Related

[Easy|Power]Mock: make constructor.newInstance(...) throw an exception?

I want to make constructor.newInstance(...) throw an exception in a unit test. I'd like to check if the else-branch is reached in the following (dummy-)code:
public <T extends IInterface> instantiate(final Constructor<IInterface> constructor) {
try {
return constructor.newInstance(arg);
} catch (Exception e) {
return null;
}
}
I'd like to reach the null case. Can I mock that without using (Power)Mockito?
I could theoretically do
class TestImplementation implements IInterface {
public TestImplementation(Arg.class) {
throw new InstantiationException("just for your test case");
}
}
But I'm curious whether or not I can achieve this with mocking.
The class java.lang.Constructor is final, so mocking is hard by default. The latest versions of Mockito support mocking final classes, EasyMock does not to my knowledge.
Thus, your choices are probably:
Mockito (latest versions, with the new experimental "mocking of final" enabled)
PowerMock(ito)
JMockit
And for the record: passing in a Class instance of some "dummy" class, like you suggest within the question is way better than using a mocking framework.
You have to understand: you don't use mocking because you can. You only use it when you have to! In your case, there is a simple, straight forward non-mocking solution to test your production code.
So: use TestImplementation.class and forget about using a mocking framework here.

How to write unit test by mocking, when you have zero arg:constructors

I was trying to write unit test using jmocks and junit. (My Project uses core java- no frameworks-) I could not write unit test for some of my classes, by mocking external dependencies, when dependencies were initialized in a a no arg-constructor.
As i cannot provide the actual code, trying to explain the scenario by an example
public interface Apple {
String variety();
}
Implementation.
public class MalgovaApple implements Apple {
#Override
public String variety() {
return "Malgova";
}
}
Class to be tested
public class VarietyChecker {
private Apple apple;
VarietyChecker(){
this.apple = new MalgovaApple();
// instead of new, a factory method is used in actual application
}
public String printAppleVariety(){
String variety = apple.variety();
if(variety.length() < 3){
System.out.println("Donot use Code names- Use complete names");
return "bad";
}
return "good";
}
}
Junit test using jmock
public class VarietyCheckerUnitTest{
Mockery context = new JUnit4Mockery();
#Before
public void setUp() throws Exception {
}
#After
public void tearDown() throws Exception {
}
#Test
public void test_VarietyChecker() throws Exception{
final Apple mockapple = context.mock(Apple.class);
VarietyChecker printer = new VarietyChecker();
context.checking(new Expectations(){{
oneOf(mockapple).variety();will(returnValue("as"));
}});
String varietyNameValid = printer.printAppleVariety();
assertEquals("bad",varietyNameValid);
} }
This test fails - Mocking does not work the values "as" is not injected, the test class executes with MalgovaApple ...
Now if we add below constructor to VarietyChecker and use it test case - it gives expected output...
public VarietyChecker(Apple apple) {
super();
this.apple = apple;
}
and in unit test create test class object like
VarietyChecker printer = new VarietyChecker(mockapple);
Exposing a new constructor just for the purpose of testing is not a good idea. After all it is said that you should not alter the code for testing alone, more than that, i am afraid we have already written "some"(amount) code...
Am i missing something in junit or jmock that can make mocking work even incase of no-arg constructors. Or is this a limitation of simple junit and jmocks and should i migrate to something powerful like Jmockit /PowerMock
You should consider two choices.
Use a constructor parameter as you describe.
In this case, you're not "exposing a new constructor just for the purpose of testing". You're making your class more flexible by allowing callers to use a different factory implementation.
Don't mock it.
In this case, you are declaring that it never makes sense to use a different factory. Sometimes this is okay. At that point, the question changes, though. Instead of, "How do I mock this?" your question is now, "What am I gaining from writing this test?" You might not be gaining much of anything, and it might not make much sense to write the test at all.
If you don't mock it and decide a unit test is still worth it, then you should be asserting on other aspects of the code. Either an end state or some output. In this case, the factory call becomes an implementation detail that's not appropriate for mocking.
It's important not to fall for a "unit test everything" mentality. That is a recipe for Test-induced Design Damage. Evaluate your tests on a case by case basis, deciding whether they're providing you any real value or not. Not writing a unit test is a valid option and is even appropriate at times, even if it's option you try very hard to avoid.
Only you can make a determination which one makes the most sense in this case. From the the fact that this is a factory object we're talking about, I'd probably lean toward the former.

JUNIT Conditional Tests possible?

I have a series of data each one containing info_A and info_B. I would like to:
if(info_A) {
run Test A
} else if(!info_A) {
run Test B
}
It is very important that only the Test actually run is shown in the JUnit GUI tree. How can I do this?
The following solutions do not work:
If I use the Assume.assumeTrue(conditon), I can Ignore a test but then it is still displayed as passed in the test.
Doing this:
Result result = JUnitCore.runClasses(TestStep1.class);
leads to the correct result but the JUnit tree is not built.
Using #Catagories also shows the failed tests, which is also what I don't want.
You can use Assume to turn tests on/off conditionally:
A set of methods useful for stating assumptions about the conditions in which a test is meaningful. A failed assumption does not mean the code is broken, but that the test provides no useful information.
You can do this with JUnit Rules.
There's a whole blog post dedicated to exactly your question here, but in short, you do the following:
Create a class that implements the org.junit.rules.TestRule interface. This interface contains the following method:
Statement apply(Statement base, Description description);
The base argument is actually your test, which you run by calling base.execute() -- well, the apply() method actually returns a Statement anonymous instance that will do that. In your anonymous Statement instance, you'll add the logic to determine whether or not the test should be run. See below for an example of a TestRule implementation that doesn't do anything except execute your test -- and yes, it's not particularly straighforward.
Once you've created your TestRule implementation, then you need to add the following lines to to your JUnit Test Class:
#Rule
public MyTestRuleImpl conditionalTests;
Remember, the field must be public.
And that's it. Good luck -- as I said, you may have to hack a little, but I believe there's a fair amount explained in the blog post. Otherwise, there should be other information on the internets (or in the JUnit sourc code).
Here's a quick example of a TestRule implementation that doesn't do anything.
public abstract class SimpleRule implements TestRule {
public Statement apply(final Statement base, final Description description) {
return new Statement() {
public void evaluate() throws Throwable {
try {
base.evaluate();
} catch (Throwable t) {
t.printStackTrace();
}
}
};
}
}

Appropriate method encapsulation for unit testing

My class contains 14 private methods and 1 public method. The public method calls all the private method directly or indirectly via other private methods.
The public method also has a call to a DAO that queries the database.
I wrote a unit test for the class. Since you can't write unit test for private methods, I changed all the private methods to default access and wrote unit test for them.
I was told that I shouldn't change the encapsulation just for the purpose of testing. But my public method has a call to the DAO and gets its data from the call. Even if I were to write a test for the public method, I'm assuming it would be really long and complicated.
How should I approach this problem. On one hand, I have to write a really complicated test for the public method which accesses a DAO and on the other hand, change the access level of the methods and write short, simple test methods for them. What should I do?
Any suggestions will be greatly appreciated
Purists will tell you that the private methods could be extracted to another helper class providing accessible methods, and they could be right.
But if it makes sense to keep these utility methods inside the class, if the class is not part of a public API and is not intended to be subclassed (it could be final, for example), I don't see any problem with making some of its private methods package-protected or protected. Especially if this non-private visibility is documented, for example with the Guava annotation #VisibleForTesting.
Seems like you have two problems here:
How to test private methods (assuming in Java):
I would look at this question: How do I test a class that has private methods, fields or inner classes?
I personally like Trumpi's response:
The best way to test a private method is via another public method. If this cannot be done, then one of the following conditions is true:
The private method is dead code
There is a design smell near the class that you are testing
The method that you are trying to test should not be private
How to break the dependency of the DAO
You could try to use Dependency Injection to get rid of your dependency on the DAO. Then you can mock out the DAO and inject it into your test case.
The benefit is it truly becomes a unit test and not an integration test.
If it's complicated, it's probably because your class have more than one responsability. Normally, when you have private methods that do different things, is that you could have different classes with public methods that do that for you. Your class will become more easy to read, to test, and you will separate responsability. 14 private methods normally indicates this kind of thing :P
For example, you could have something like
public class LeFooService {
private final OtherServiceForConversion barService;
private final FooDao fooDao;
public LeeFooService(FooDao dao, OtherServiceForConversion barService) {
this.barService = barService;
this.fooDao = dao;
}
public void createAsFoo(Bar bar) throws ConversionException {
Foo foo = convert(bar);
fooDao.create(foo);
}
private Foo convert(Bar bar) {
// lots of conversion stuff, services calling D:
}
}
for testing correctly, you will have to test if conversion was done correctly. Because it's private, you will have to capture the foo sent to FooDao and see if all fields were set correctly. You can use argThat to capture what's sent to fooDao to test the conversion then. Your test would look something like
....
#Test
public void shouldHaveConvertedFooCorrectly() {
// given
Bar bar = mock(Bar.class);
// when
fooService.createAsFoo(bar);
// then
verify(fooDao).create(argThat(fooIsConvertedCorrectly());
}
private ArgumentMatcher<Foo> fooIsConvertedCorrectly() {
return new ArgumentMatcher<Foo>() { /*test stuff*/ };
}
....
But, if you separated the conversion to another class, like this:
public class LeFooService {
private final BarToFooConverter bar2FooConverter;
private final FooDao fooDao;
public LeeFooService(FooDao dao, BarToFooConverter bar2FooConverter) {
this.bar2FooConverter = bar2FooConverter;
this.fooDao = dao;
}
public void createAsFoo(Bar bar) throws ConversionException {
Foo foo = bar2FooConverter.convert(bar);
fooDao.create(foo);
}
}
you will be able to test what's really important to LeeFooService: The flow of the calls. The tests of the conversion from Foo to Bar will be the responsability of the unit tests from BarToFooConverter. An example test of LeeFooService would be
#RunWith(MockitoJUnitRunner.class)
public class LeFooServiceTest {
#Mock
private FooDao fooDao;
#Mock
private BarToFooConverter converter;
#InjectMocks
private LeeFooService service;
#Test(expected = ConversionException.class)
public void shouldForwardConversionException() {
// given
given(converter.convert(Mockito.any(Bar.class))
.willThrown(ConversionException.class);
// when
service.createAsFoo(mock(Bar.class));
// then should have thrown exception
}
#Test
public void shouldCreateConvertedFooAtDatabase() {
// given
Foo convertedFoo = mock(Foo.class);
given(converter.convert(Mockito.any(Bar.class))
.willReturn(convertedFoo);
// when
service.createAsFoo(mock(Bar.class));
// then
verify(fooDao).create(convertedFoo);
}
}
Hope that helped somehow :)
Some links that might be useful:
SOLID
BDD Mockito
As a parent would tell their child: DON'T EXPOSE YOUR PRIVATES!
You don't need to expose your private methods to test them. You can get 100 PERCENT test coverage of your class, including those private methods, without exposing them.
The rub is that some people think the 'unit' in unit testing is the function, when it's really the class.
For example: I have a class with 1 public method:
bool CheckIfPalindrome(string wordToCheck).
Internally, I have private methods to validate the length of the wordToCheck, if it's null, if it's empty, bla bla bla.
But as the tester, I don't need to know or care about how I the developer organized (or will organize) the internal code. I'm testing the implementation of the interface.
'Given the word is "Mike", When CheckIfPalindronme is called, it should return false'
'Given the word is "Mom", When CheckIfPalindronme is called, it should return true'
'Given the word is "", When CheckIfPalindronme is called, it should return false'
'Given the word is null, When CheckIfPalindronme is called, it should throw an error'
If I cover all of the possible inputs and expected outputs, I will be testing your private functions.
This is the basis of TDD / BDD, without this, TDD wouldn't be possible because we would have to wait and see how did you decide to organize your code before we can write our test.
TDD / BDD says write your tests before you even write your code (and it works great btw! It identifies flaws in requirements / design very quickly)
A class containing one public method and 14 private methods, is close to impossible to test. Without having seen it, I would be willing to bet, that it is very un-SOLID. Like JB Nizet says; me and my purist colleaagues would extract most or all private methods to helper classes. The reasons are:
Easy to test
Easy to refactor
Easy to read
Easy to reuse
The reason not to extract:
* A lot!! of classes
* It takes time to extract
* At times, performance issues hinder the pretty-ness of "proper" design.
IMHO extraction of logic should always be considered in case of:
Private methods
Big classes (I usually start to think of it when
the vertical scrollbar appears in my editor winow )
Loops within
loops
The keyword here is Single Responsibility (SRP).

How to do unit test for Exceptions?

As you know, exception is thrown at the condition of abnormal scenarios. So how to analog these exceptions? I feel it is challenge. For such code snippets:
public String getServerName() {
try {
InetAddress addr = InetAddress.getLocalHost();
String hostname = addr.getHostName();
return hostname;
}
catch (Exception e) {
e.printStackTrace();
return "";
}
}
Does anybody have good ideas?
You can tell junit that the correct behavior is to get an exception.
In JUnit 4, it goes something like:
#Test(expected = MyExceptionClass.class)
public void functionUnderTest() {
…
}
Other answers have addressed the general problem of how to write a unit test that checks that an exception is thrown. But I think your question is really asking about how to get the code to throw the exception in the first place.
Take your code as an example. It would be very hard to cause your getServerName() to internally throw an exception in the context of a simple unit test. The problem is that in order for the exception to happen, the code (typically) needs to be run on a machine whose networking is broken. Arranging for that to happen in a unit test is probably impossible ... you'd need to deliberately misconfigure the machine before running the test.
So what is the answer?
In some cases, the simple answer is just to take the pragmatic decision and not go for total test coverage. Your method is a good example. It should be clear from code inspection what the method actually does. Testing it is not going to prove anything (except see below **). All you are doing is improve your test counts and test coverage numbers, neither of which should be project goals.
In other cases, it may be sensible to separate out the low-level code where the exception is being generated and make it a separate class. Then, to test the higher level code's handling of the exception, you can replace the class with a mock class that will throw the desired exceptions.
Here is your example given this "treatment". (This is a bit contrived ... )
public interface ILocalDetails {
InetAddress getLocalHost() throws UnknownHostException;
...
}
public class LocalDetails implements ILocalDetails {
public InetAddress getLocalHost() throws UnknownHostException {
return InetAddress.getLocalHost();
}
}
public class SomeClass {
private ILocalDetails local = new LocalDetails(); // or something ...
...
public String getServerName() {
try {
InetAddress addr = local.getLocalHost();
return addr.getHostName();
}
catch (Exception e) {
e.printStackTrace();
return "";
}
}
}
Now to unit test this, you create a "mock" implementation of the ILocalDetails interface whose getLocalHost() method throws the exception you want under the appropriate conditions. Then you create a unit text for SomeClass.getServerName(), arranging that the instance of SomeClass uses an instance of your "mock" class instead of the normal one. (The last bit could be done using a mocking framework, by exposing a setter for the local attribute or by using the reflection APIs.)
Obviously, you would need to modify your code to make it testable like this. And there are limits to what you can do ... for example, you now cannot create a unit test to make the real LocalDetails.getLocalHost() method to throw an exception. You need to make a case-by-case judgement as to whether it is worth the effort of doing this; i.e. does the benefit of the unit test outweigh the work (and extra code complexity) of making the class testable in this way. (The fact that there is a static method at the bottom of this is a large part of the problem.)
** There is a hypothetical point to this kind of testing. In your example, the fact that the original code catches an exception and returns an empty string could be a bug ... depending on how the method's API is specified ... and a hypothetical unit test would pick it up. However, in this case, the bug is so blatant that you would spot it while writing the unit test! And assuming that you fix bugs as you find them, the unit test becomes somewhat redundant. (You wouldn't expect someone to re-instate this particular bug ...)
Okay there are a few possible answers here.
Testing for an exception itself is easy
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
#Test
public void TestForException() {
try {
doSomething();
fail();
} catch (Exception e) {
assertThat(e.getMessage(), is("Something bad happened"));
}
}
Alternately, you can use the Exception Annotation to note that you expect an exception to come out.
Now, as to you specific example, Testing that something you are creating inside your method, either via new or statically as you did, when you have no way to interact with the object is tricky. You normally need to encapsulate that particular generator and then use some mocking to be able to override the behavior to generate the exception you expect.
Since this question is in community wiki I'll add a new one for completeness:
You can use ExpectedException in JUnit 4
#Rule
public ExpectedException thrown= ExpectedException.none();
#Test
public void TestForException(){
thrown.expect(SomeException.class);
DoSomething();
}
The ExpectedException makes the thrown exception available to all test methods.
Is is also possible to test for a specific error message:
thrown.expectMessage("Error string");
or use matchers
thrown.expectMessage(startsWith("Specific start"));
This is shorter and more convenient than
public void TestForException(){
try{
DoSomething();
Fail();
}catch(Exception e) {
Assert.That(e.msg, Is("Bad thing happened"))
}
}
because if you forget the fail, the test can result in a false negative.
Many unit testing frameworks allow your tests to expect exceptions as part of the test. JUnit, for example, allows for this.
#Test (expected=IndexOutOfBoundsException.class) public void elementAt() {
int[] intArray = new int[10];
int i = intArray[20]; // Should throw IndexOutOfBoundsException
}

Categories