Mockito not resetting - java

I have a tests, that when they run individually work fine. However when i run them together one always fail expecting total invocations accross both tests rather than one.
I have added Mockito.reset in the before and after method, but to no avail.
private Logic mockTest = Mockito.mock(Logic.class);
#Before
public void createMocks() {
Mockito.reset(mockTest);
}
#Test
public void TestGameList() {
Mockito.when(mockTest.getGame()).thenReturn(null);
Mockito.verify(mockTest, Mockito.times(1)).getGame();
}
#Test
public void TestGame2List() {
Mockito.when(mockTest.getGame()).thenReturn(null);
Mockito.verify(mockTest, Mockito.times(1)).getGame();
}
Why doesnt reset work?
I have tried VerificationModeFactory to count it, but that doesnt work either

Use one of the following:
#Mock
private Logic mockTest;
#Before
public void createMocks() {
MockitoAnnotiation.initMocks(this);
}
or
private Logic mockTest;
#Before
public void createMocks() {
mockTest = Mockito.mock(Logic.class);
}
Either way you will create an entirely new mock for each test thereby ensuring that no state is maintained across tests.

Related

JUnit 5 AfterAllTests feature

Is there a way to execute "AfterAllTests" action within JUnit 5? E.g. close connection to db, close embedded kafka cluster, etc.
P.S. There is a way to do some preconditions before all tests with help of extension like that:
public class BeforeAfterExtension implements BeforeAllCallback, AfterAllCallback {
private static boolean FLAG = Boolean.TRUE;
...
#Override
public void beforeAll(ExtensionContext extensionContext) {
log.info("~~~~~~~~~~~~~~~~~~ BeforeAll setup ~~~~~~~~~~~~~~~~~~");
if (FLAG) {
// some code here
FLAG = Boolean.FALSE;
}
}
#Override
public void afterAll(ExtensionContext extensionContext) {
// ??
}
But no way for "After" tasks.
Yes you can use below mentioned code.
#AfterAll
static void afterAllIAmCalled() {
System.out.println("---Inside after finishing all testsDownAll---");
}
Link for you: https://www.concretepage.com/testing/junit-5/junit-5-beforeall-and-afterall-example
Updating answer further based on your need of running after all sets. Define your tests in suite as shown below
#RunWith(Suite.class)
# Suite.SuiteClasses({
SuiteTest1.class,
SuiteTest2.class,
})
public class JunitTest {
// This class remains empty, it is used only as a holder for the above annotations but as you need to perform action at the end of it do as mentioned below
#AfterSuite
Private void methodName(){
//my suite end action
}
}
Replied on mobile. Might not be symmetric answer but will solve your problem.
This should work for you.

How to use JUnit4TestAdapter with objects

I am trying to write a test suite using JUnit4 by relying on JUnit4TestAdapter. Having a look at the code of this class I saw that it only works with a Class as input. I would like to build a test class and set a parameter on it before running it with my TestSuite. Unfortunately, Junit4TestAdapter is building the test by using reflection (not 100% sure about the mechanism behind it), which means that I cannot change my test class on runtime.
Has anybody done anything similar before? Is there any possible workaround to this issue? Thanks for your help!
public class SimpleTest {
#Test
public void testBasic() {
TemplateTester tester = new TemplateTester();
ActionIconsTest test = new ActionIconsTest();
test.setParameter("New Param Value");
tester.addTests(test);
tester.run();
}
}
/////
public class TemplateTester {
private TestSuite suite;
public TemplateTester() {
suite = new TestSuite();
}
public void addTests(TemplateTest... tests) {
for (TemplateTest test : tests) {
suite.addTest(new JUnit4TestAdapter(test.getClass()));
}
}
public void run() {
suite.run(new TestResult());
}
}
/////
public interface TemplateTest {
}
/////
public class ActionIconsTest extends BaseTestStrategy implements TemplateTest {
#Test
public void icons() {
//Test logic here
}
public void navigateToTestPage() {
//Here I need the parameter
}
}
/////
public abstract class BaseTestStrategy {
protected String parameter;
#Before
public void init() {
navigateToTestPage();
}
public abstract void navigateToTestPage();
public void setParameter(String parameter) {
this.parameter = parameter;
}
}
I am trying to test a web application with Selenium. The way I want to test is by splitting the functionality, e.g., I want to test the available icons (ActionIconsTest), then I'd like to test other parts like buttons, etc.
The idea behind this is to have a better categorization of the functionality available in certain screen. This is quite coupled with the way we are currently developing our web app.
With this in mind, TemplateTest is just an interface implemented by the different kind of tests (ActionIconTest, ButtonTest, etc) available in my system.
TemplateTester is a Junit suite test with all the different tests that implement the interface TemplateTest.
The reason for this question is because I was trying to implement a Strategy pattern and then realized of the inconvenient of passing a class to Junit4TestAdapter in runtime.
Well, taking in account that JUNIT needs your tester's Class object as an object factory (so he can create several instances of your tester), I can only suggest you pass parameters to your tester through System Properties.
Moreover, it's the recommended way of passing parameters: http://junit.org/faq.html#running_7

Alternative of mocking a static method present in some jar

I know that if I need to mock a static method, this indicates that my design has some issue, but in my case this does not seem to be a design issue.
BundleContext bundleContext = FrameworkUtil.getBundle(ConfigService.class).getBundleContext();
Here FrameworkUtil is a class present in an api jar. Using it in code cant be a design issue.
my problem here is while running this line
FrameworkUtil.getBundle(ConfigService.class);
returns null So my question, is there any way by which I can replace that null at runtime
I am using Mockito framewrok and my project does not allow me to use powermock.
if I use
doReturn(bundle).when(FrameworkUtil.class)
in this way getBundle method is not visible since its a static method.
You are correct that is not a design issue on your part. Without PowerMock, your options become a bit murkier, though.
I would suggest creating a non-static wrapper for the FrameworkUtil class that you can inject and mock.
Update: (David Wallace)
So you add a new class to your application, something like this
public class UtilWrapper {
public Bundle getBundle(Class<?> theClass) {
return FrameworkUtil.getBundle(theClass);
}
}
This class is so simple that you don't need to unit test it. As a general principle, you should only EVER write unit tests for methods that have some kind of logic to them - branching, looping or exception handling. One-liners should NOT be unit tested.
Now, within your application code, add a field of type UtilWrapper, and a setter for it, to every class that currently calls FrameworkUtil.getBundle. Add this line to the construtor of each such class
utilWrapper = new UtilWrapper();
And replace every call to FrameworkUtil.getBundle with utilWrapper.getBundle.
Now in your test, you make a mock UtilWrapper and stub it to return whatever Bundle you like.
when(mockUtilWrapper.getBundle(ConfigService.class)).thenReturn(someBundleYouMade);
and for the class that you're testing, call setUtilWrapper(mockUtilWrapper) or whatever. You don't need this last step if you're using #InjectMocks.
Now your test should all hang together, but using your mocked UtilWrapper instead of the one that relies on FrameworkUtil.
unit test
package x;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
public class GunTest {
#Before
public void setUp() throws Exception {
}
#Test
public void testFireTrue() {
final Gun unit = Mockito.spy(new Gun());
Mockito.doReturn(5).when(unit).getCount();
assertTrue(unit.fire2());
}
#Test
public void testFireFalse() {
final Gun unit = Mockito.spy(new Gun());
Mockito.doReturn(15).when(unit).getCount();
assertFalse(unit.fire2());
}
}
the unit:
fire calls the static method directly,
fire2 factors out the static call to a protected method:
package x;
public class Gun {
public boolean fire() {
if (StaticClass.getCount() > 10) {
return false;
}
else {
return true;
}
}
public boolean fire2() {
if (getCount() > 10) {
return false;
}
else {
return true;
}
}
protected int getCount() {
return StaticClass.getCount();
}
}

How to write database integration test properly in Play 2.1?

I am new at Play! 2.1. I'm trying to TDD my database integration test. After reading the examples on the website. I wrote my test like this.
#Test
public void shouldGetDealName() {
running(fakeApplication(), new Runnable() {
public void run() {
List books = Book.find.all();
Assert.assertEquals(books.size(), 1);
}
});
}
My question would be, do I need to wrap the code in running(fakeAppliation()... all the time? Because if I run this code without the fakeApplication. It doesn't seem to work. If it has to be like that then is there a better way to do this in Java? It seems wrong for me to wrap the code in that block every time for integration or functional test.
Thanks.
You can do it this way, assuming you want to use in-memory DB and you want it to be recreated for each test:
public class ApplicationTest extends WithApplication {
#Before
public void setup() {
start(fakeApplication(inMemoryDatabase(), fakeGlobal()));
}
#Test
public void shouldGetDealName() {
List books = Book.find.all();
Assert.assertEquals(books.size(), 1);
}
}

JUnit: Run one test with different configurations

I have 2 test methods, and i need to run them with different configurations
myTest() {
.....
.....
}
#Test
myTest_c1() {
setConf1();
myTest();
}
#Test
myTest_c2() {
setConf2();
myTest();
}
//------------------
nextTest() {
.....
.....
}
#Test
nextTest_c1() {
setConf1();
nextTest();
}
#Test
nextTest_c2() {
setConf2();
nextTest();
}
I cannot run them both from one config (as in code below) because i need separate methods for tosca execution.
#Test
tests_c1() {
setConf1();
myTest()
nextTest();
}
I don't want to write those 2 methods to run each test, how can i solve this?
First i thought to write custom annotation
#Test
#RunWithBothConf
myTest() {
....
}
But maybe there are any other solutions for this?
What about using Theories?
#RunWith(Theories.class)
public class MyTest{
private static enum Configs{
C1, C2, C3;
}
#DataPoints
public static Configs[] configValues = Configs.values();
private void doConfig(Configs config){
swich(config){...}
}
#Theory
public void test1(Config config){
doConfig(config);
// rest of test
}
#Theory
public void test2(Config config){
doConfig(config);
// rest of test
}
Not sure why formatting if off.
I have a similar issue in a bunch of test cases I have, where certain tests need to be run with different configurations. Now, 'configuration' in your case might be more like settings, in which case maybe this isn't the best option, but for me it's more like a deployment model, so it fits.
Create a base class containing the tests.
Extend the base class with one that represents the different configuration.
As you execute each of the derived classes, the tests in the base class will be run with the configuration setup in its own class.
To add new tests, you just need to add them to the base class.
Here is how I would approach it:
Create two test classes
The first class configures to conf1 but uses the #Before attribute trigger the setup
The second class extends the first but overrides the configure method
In the example below I have a single member variable conf. If no configuration is run it stays at its default value 0. setConf1 is now setConf in the Conf1Test class which sets this variable to 1. setConf2 is now setConf in the Conf2Test class.
Here is the main test class:
public class Conf1Test
{
protected int conf = 0;
#Before
public void setConf()
{
conf = 1;
}
#Test
public void myTest()
{
System.out.println("starting myTest; conf=" + conf);
}
#Test
public void nextTest()
{
System.out.println("starting nextTest; conf=" + conf);
}
}
And the second test class
public class Conf2Test extends Conf1Test
{
// override setConf to do "setConf2" function
public void setConf()
{
conf = 2;
}
}
When I configure my IDE to run all tests in the package I get the following output:
starting myTest; conf=1
starting nextTest; conf=1
starting myTest; conf=2
starting nextTest; conf=2
I think this gives you what. Each test only has to be written once. Each test gets run twice, once with conf1 and once with conf2
The way you have it right now seems fine to me. You aren't duplicating any code, and each test is clear and easy to understand.

Categories