Anyway to create a Test Helper class that creates mocks? - java

In my testing of a legacy system, I have found myself having to mock similar classes for different parts of the system I'm increasing test coverage for. I would like to create a helper class for my tests that could call a method that would set up particular mocks and their return values.
Here's an example of a method I have had to create a few times in multiple tests.
public void mockClassINeedToMockToReturn(Boolean bool){
mockStatic(classINeedToMock.class);
when(classINeedToMock.getSuccess(Mockito.any(someClass.class))).thenReturn(bool);
}
I have tried setting this up in a HelperTest.class (in the same project/folder as my tests) and it isn't working. I have included both the following Annotations in the class.
#RunWith(PowerMockRunner.class)
#PrepareForTest({classINeedToMock.class})
I have tried:
Using the methods statically and calling them in my tests. (does not mock)
Creating a HelperTest object and calling the method in my test. (still does not mock)
Having my tests Extend my HelperTest.class and calling the method from in my tests. (Still refuses to mock the class)
I'm sure this is something to do with the way the PowerMockRunner works. So is there a way to make this work? Or should I just come to terms with duplicating these methods throughout my project.

It's the little details.... When looking into it more I noticed the class I was mocking had 2 separate methods.
theClass.method(var1, var2);
theClass.method(var1, List<var2>);
One of my tests was calling the first method, the other was calling the second method. When I ran the second test (only having mocked the first method), it was calling the actual class because that method was not mocked.
After setting up the correct mock with the proper input parameters I could call the method statically and the mock would be created and used appropriately.

Related

How to get test method (or name) in JUnit 5 test class constructor?

I'm writing a very simple tests in JUnit 5 and wonder if it is at all possible to get the name or reference to the test method being executed in the constructor of the test class. I'm using a default approach of a separate test case instance per test method, so technically it should be possible. I was toying with TestInfo interface, but that one injected into constructor does not bear method context. Is there a different way of achieving this?

Can I make code run before the constructor using annotations

I am using Guice to create and inject instances in my application.
For testing purposes I created a class that is responsible for creating all the static instances needed for a specific test class and inject them. Let's call this class GuiceGraphBuilder.
I want to create and initiate the GuiceGraphBuilder before my mock / test class constructor is called, as some of my mock classes requires the injection to happen on construction time.
Currently I am using a static constructor that initiate GuiceGraphBuilder and populate bunch of static fields.
Is there a way to use some kind of annotation to make a code run before the constructor does?
I have seen an answer that uses Guice, but this of course is not good in my case, since I want to create the Guice injector in the generated code.
I suppose you test using junit? Then you have the lifecycle hooks
#BeforeClass - run once before first test (use for static setup)
#Before - run before every test method
#After - run after each test method
#AfterClass - run once after all tests finished
I suppose that, arbitrary from guice, you will be able to solve your problem by matching init and clean up to the correct phase.

PowerMock, how to make a static method return value more than once?

This may be a simple question, but I could not find an answer with reasonable search.
I am trying to make a static method return a value more than once in multiple tests. I fail to achieve this with the mocked static method with PowerMock. To put this simply I have a JUnit test #BeforeClass like this
#RunWith(PowerMockRunner.class)
#PrepareForTest(StaticStuff.class)
public class MyTest extends TestCase {
#BeforeClass
public static void init() {
// Mock some stuff
PowerMockito.mockStatic(StaticStuff.class);
Mockito.when(StaticStuff.get()).thenReturn("something");
}
}
Now, this works for the first test accessing the static method, but the rest will receive 'null' (update: or any other value that the "real" method would return). I can fix the problem simply changing the #BeforeClass to #Before, thus making the static mock be recreated for every test. But afaik, this is not the correct way to do this. For this particular case this will do, but I believe there should be a way to provide information that the method may be called "any times".
Actually I understood from the documentation that the same value should be returned "infinite times by default" (but it doesn't. From Mockito documentation: 'Once stubbed, mocked method will always return stubbed value regardless of how many times it is called.'). Also I would expect that stating the amount of calls should be something this simple (but it isn't):
Mockito.when(StaticStuff.get()).thenReturn("something").times(10);
Maybe I am just missing something?
The tests should be independent from each other. If you use JUnit, the order of the tests is not determined at all (see https://github.com/junit-team/junit/wiki/Test-execution-order). I think creating mocks in #BeforeClass is actually a bad practice, since it can cause that the tests are depending on each other. So I would simply recommend to use #Before method to initialize all mocks, and use #BeforeClass only, if you prepare something really common for the tests (like a connection pool or something like that).

#BeforeClass annotation: Junit vs TestNG

Why the #BeforeClass method in JUnit is static whereas in TestNG its non-static? TestNG was developed as an improvement over JUnit, so why did they choose this way of implementation?
Since #BeforeClass runs only once, so making it static makes more sense than making it non static. Also in TestNG, on which instance the #BeforeClass method is called? Can someone cite an example for better understanding?
The main difference between JUnit and TestNG is the test class instantiation. JUnit always creates a new instance of the test class for each test method run. TestNG only creates one test class instance and then runs all test methods of this instance.
The JUnit approach guarantees the independency of all test methods. It just does not matter, in which order they run. Additionally, all instance fields are always setup the same for each test method. Initializing data, that is common for all test methods, must take place at the class level, thus it must be static. This is the reason, why the #BeforeClass method must be static.
The TestNG approch does not guarante the independency. In fact, you cannot use an instance field in the same manner as in JUnit tests. If you change such a field in one test method, the changed value is still observabl in another test method. However, this behavior has also an advantage: Sometimes there are dependencies between some test methods. With TestNG, a tester can express them.
Because of the one-instance-approach of TestNG, the #BeforeClass setup can also be a non-static method, but it is still run only once. It was a design decision, but testers using TestNG must be aware of that.
Making a method static or non-static has nothing to do with being able to invoke that method only once at the beginning. You can call a static method as many times as you want. You can call a non-static method exactly one. There is no necessary correlation between the two : being static and invoking once. At least, I am not aware of any direct consequence of making a method static which enables it to be invoked exactly once. static is rightly associated with single class, but not with single invocation.
Making a method static prevents it from accessing non-static members of the class. But with having a non-static #BeforeClass method, you can also access non-static members, there by giving you more scope to access class variables. Perhaps this is the reason why testng removed the restriction of #BeforeClass method being static.

Junit and Mockito: How to test whether a method calls a method?

I'm trying to wrap my head around mockito and was wondering how I would test if a method calls a method!
So here is class with its method inside it:
public class RegisterController {
public void regHandle(UserDataObject user1){
ValidateRegisterInputController validate = new ValidateRegisterInputController();
validate.validateInputHandle(user1); }
How would I test that regHandle(UserDataObject) calls validate.validateInputHandle(user1); ?
I'm sure this is a super simple test, but I really can't figure out how to test this.
There are various ways of writing a test for a method which instantiates some other class. I wrote about two of them in my article on the Mockito wiki, at http://code.google.com/p/mockito/wiki/MockingObjectCreation
Both the techniques that I describe involve refactoring your code to make it more testable.
You would create a mock of ValidateRegisterInputController and then pass it on construction, then you would do:
Mockito.verify(mock).validateInputHandle(user1).
I strongly suggest you do not do this type of testing though. Instead of that, ask yourself how can you write an unit test that checks that what you wanted to validate was valid.
for example, check that after calling regHandle user1.isValid() is equals to true.

Categories