Stub all the method call including a method call inside it, from another class using mockito - mockito

How to stub a System.currentTimeMillis() in the classB from classA?
Class A:
public classA {
#Test public void timeTest() {
PowerMockito.mockStatic(System.class);
PowerMockito.when(System.currentTimeMillis()).thenReturn(10L);
B.testPowerMock(); }
}
Class B:
public class B {
public static void testPowerMock() {
System.out.println(System.currentTimeMillis());
}
}

Related

Constructor injection with mocked object which has to set mocked value in constructor

I'm trying to mock a class FooB, which has another component FooA injected via constructor injection. My problem is, that in constructor FooB a value from injected component FooA has to be set. My problem I don't know the way how to mock FooA. Usually I would do something like in the commented out code in a #BeforeAll and mock the value with Mockito.when. But at this stage FooB is already initialized.
#ExtendWith(SpringExtension.class)
#ContextConfiguration(classes = { FooB.class })
class FooTest {
#MockBean
private FooA fooA;
#Autowired
private FooB fooB;
// #BeforeAll
// void initMocks() {
// when(fooA.getFoo()).thenReturn("foo");
// }
}
#Component
public class FooB {
private final String foo;
public FooB(final FooA fooA) {
this.foo = fooA.getFoo(); // <- how do I get the mocked value in here?
}
}
#Component
public class FooA {
private String foo;
public String getFoo() {
return foo;
}
public void setFoo(final String foo) {
this.foo = foo;
}
}
The below code could solve what you are trying to do (Edit : Added both a test case that uses #SrringBootTest and without it as well)
If not using SpringBoot
#ExtendWith(SpringExtension.class)
#ContextConfiguration(classes = {FooB.class, FooTest.TestConfig.class})
class FooTest {
#Autowired
private FooB fooB;
#TestConfiguration
public static class TestConfig {
#Bean
FooA getFooA(){
FooA fooA = Mockito.mock(FooA.class);
when(fooA.getFoo()).thenReturn("foo from test");
return fooA;
}
}
#Test
void testFooB() {
assertEquals("foo from test", fooB.getFoo());
}
}
If using SpringBoot
#SpringBootTest
class FooTest {
#Autowired
private FooB fooB;
#TestConfiguration
public static class TestConfig {
#MockBean
private FooA fooA;
#PostConstruct
void initMocks() {
when(fooA.getFoo()).thenReturn("foo from test");
}
}
#Test
void testFooB() {
assertEquals("foo from test", fooB.getFoo());
}
}

When clause in Mockito JUnit is not working while calling method of testing class

I am trying to stub method of testing class. And it is not working.
Like am testing below class
enter code here
Class to test:
public Class A{
public String method1(){
C c=new C();
int num=c.methodC();
B b=new B();
String str=method2(b);
return str;
}
public String method2(B b){
String str=method2(b);
return str;
}
}
JUnit class:
#RunWith(JUnitPlatform.class)
Class ATest {
#InjectMocks
A a;
#Mock
C c;
#Mock
A a1;
#BeforeEach
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
#Test
public void testMethod1(){
Mockito.doReturn(34).when(c).methodC(anyString());
a1=Mockito.mock(A.class);
Mockito.doReturn("Added successfully").when(a1).method2(any(B.class));
assertEquals("Added successfully", a.method1());
}
}
When am stubbing methodC(...) from Class C it is working. But method2(...) from Class A is not stubbing.
Please let me know what is the issue, and solution.
You have 2 options to mocka parts of the object.
Option 1: use a #Spy instead of a #Mock
#ExtendWith(MockitoExtension.class)
class ATest {
#Spy
A a;
#Test
public void testMethod1() {
Mockito.doReturn("Added successfully").when(a).method2(any(B.class));
assertEquals("Added successfully", a.method1());
}
}
Option 2: Use a mock and mark real implementations
#ExtendWith(MockitoExtension.class)
class ATest {
#Mock
A a;
#Test
public void testMethod1() {
Mockito.doReturn("Added successfully").when(a).method2(any(B.class));
Mockito.doCallRealMethod().when(a).method1();
assertEquals("Added successfully", a.method1());
}
}
I found via trial and error method that, methods in testing class cannot be mocked. In case we have to mock a method, either we have to move such methods to different class, or do not mock it. That is the only solution.

How to use the mock object of the test class and call main method from the test class

In the test class trying to test the main method and not sure how to use the mock object here.
How to use the mock object orders to call the main method and it's methods inside the main method
Any suggestions on how this can be done?
public class Orders {
public static void main(String[] s) {
Orders jp = new Orders();
jp.method1();
List<OrderItems> lstOrdItms = jp.getListOrderItems();
jp.processOrderItems( lstOrdItms );
}
public void method1(List<OrderItem> lstOrderItem) {
.........
}
public List<OrderItem> getListOrderItems() {
............
}
public void processOrderItems() {
............
}
}
public class OrdersTest {
#Mocks
Orders orders;
.....
#Before
public void setUp() {
........
}
#Test
public void testMain() throws SQLException {
// Not sure how to test here
// This will actually execute the main method instead of mock.
orders.main(new String[]{});
}
}

Is threre any way to ues override method in anonymous class on Groovy #CompileStatic annotation

Is threre any way to ues override method in anonymous class on Groovy #CompileStatic annotation?
groogy source
import groovy.transform.CompileStatic;
interface HelloWorld {
public void greet();
}
class HelloWorldAnonymousClassesParents {
public void hi() {
println "hi"
}
}
#CompileStatic
public class HelloWorldAnonymousClasses extends HelloWorldAnonymousClassesParents {
public void hi() {
System.out.println("hihi ");
}
public void sayHello() {
HelloWorld spanishGreeting = new HelloWorld() {
public void greet() {
hi() //<- here [Static type checking] - Reference to method is ambiguous error
System.out.println("spanishGreeting");
}
};
spanishGreeting.greet();
hi()
}
}
def myApp = new HelloWorldAnonymousClasses();
myApp.sayHello();
Same source in java run well
java source
package org.octopus;
class HelloWorldAnonymousClassesParents {
public void hi() {
System.out.println("hi ");
}
}
interface HelloWorld {
public void greet();
}
public class Test extends HelloWorldAnonymousClassesParents{
public void hi() {
System.out.println("hihi ");
}
public void sayHello() {
HelloWorld spanishGreeting = new HelloWorld() {
public void greet() {
hi();
System.out.println("spanishGreeting");
}
};
spanishGreeting.greet();
hi();
}
public static void main(String... args) {
Test myApp = new Test();
myApp.sayHello();
}
}
How can I avoid that error with #CompileStatic annotation?
You can write it as a closure. This implies an as HelloWorld and as the interface only has one method groovy can deduct this.
HelloWorld spanishGreeting = {
hi()
System.out.println("spanishGreeting");
}
above code is groovy 2.3; with earlier groovy 2 versions it needs an explicit cast like
def spanishGreeting = {/*...*/} as HelloWorld

Groovy Inner Classes wont work with Apache Wicket

Im trying to write simple things with Apache Wicket (6.15.0) and Groovy (2.2.2 or 2.3.1). And Im having trouble with inner classes.
class CreatePaymentPanel extends Panel {
public CreatePaymentPanel(String id) {
super(id)
add(new PaymentSelectFragment('currentPanel').setOutputMarkupId(true))
}
public class PaymentSelectFragment extends Fragment {
public PaymentSelectFragment(String id) {
super(id, 'selectFragment', CreatePaymentPanel.this) // problem here
add(new AjaxLink('cardButton') {
#Override
void onClick(AjaxRequestTarget target) {
... CreatePaymentPanel.this // not accessible here
}
})
add(new AjaxLink('terminalButton') {
#Override
void onClick(AjaxRequestTarget target) {
... CreatePaymentPanel.this // not accessible here
}
});
}
} // end of PaymentSelectFragment class
} // end of CreatePaymentPanel class
Groovy tries to find a property "this" in CreatePaymentPanel class.. How to workaround this? It is a valid java code, but not groovy.
However,
Test.groovy:
class Test {
static void main(String[] args) {
def a = new A()
}
static class A {
A() {
def c = new C()
}
public void sayA() { println 'saying A' }
class B {
public B(A instance) {
A.this.sayA()
instance.sayA()
}
}
/**
* The problem occurs here
*/
class C extends B {
public C() {
super(A.this) // groovy tries to find property "this" in A class
sayA()
}
}
}
}
Above code wont work, the same error occurs, like in Wicket's case.
And TestJava.java, the same and working:
public class TestJava {
public static void main(String[] args) {
A a = new A();
}
static class A {
A() {
C c = new C();
}
public void sayA() {
System.out.println("saying A");
}
class B {
public B(A instance) {
instance.sayA();
}
}
/**
* This works fine
*/
class C extends B {
public C() {
super(A.this);
sayA();
}
}
}
}
What I am missing?
You can't refer to a CreatePaymentPanel.this inside of PaymentSelectFragment because there is no instance of CreatePamentPanel that would be accessible there. What would you expect that to evaluate to if it were allowed?

Resources