Best Mockito code snippet using org.mockitousage.stubbing.StubbingWithDelegateTest
Source: StubbingWithDelegateTest.java
...14import org.mockito.exceptions.base.MockitoException;15import org.mockitousage.IMethods;16import org.mockitousage.MethodsImpl;17@SuppressWarnings("unchecked")18public class StubbingWithDelegateTest {19 public class FakeList<T> {20 private T value;21 public T get(int i) {22 return value;23 }24 public T set(int i, T value) {25 this.value = value;26 return value;27 }28 public int size() {29 return 10;30 }31 public ArrayList<T> subList(int fromIndex, int toIndex) {32 return new ArrayList<T>();33 }34 }35 public class FakeListWithWrongMethods<T> {36 public double size() {37 return 10;38 }39 public Collection<T> subList(int fromIndex, int toIndex) {40 return new ArrayList<T>();41 }42 }43 @Test44 public void when_not_stubbed_delegate_should_be_called() {45 List<String> delegatedList = new ArrayList<String>();46 delegatedList.add("un");47 List<String> mock = Mockito.mock(List.class, AdditionalAnswers.delegatesTo(delegatedList));48 mock.add("two");49 Assert.assertEquals(2, mock.size());50 }51 @Test52 public void when_stubbed_the_delegate_should_not_be_called() {53 List<String> delegatedList = new ArrayList<String>();54 delegatedList.add("un");55 List<String> mock = Mockito.mock(List.class, AdditionalAnswers.delegatesTo(delegatedList));56 Mockito.doReturn(10).when(mock).size();57 mock.add("two");58 Assert.assertEquals(10, mock.size());59 Assert.assertEquals(2, delegatedList.size());60 }61 @Test62 public void delegate_should_not_be_called_when_stubbed2() {63 List<String> delegatedList = new ArrayList<String>();64 delegatedList.add("un");65 List<String> mockedList = Mockito.mock(List.class, AdditionalAnswers.delegatesTo(delegatedList));66 Mockito.doReturn(false).when(mockedList).add(Mockito.anyString());67 mockedList.add("two");68 Assert.assertEquals(1, mockedList.size());69 Assert.assertEquals(1, delegatedList.size());70 }71 @Test72 public void null_wrapper_dont_throw_exception_from_org_mockito_package() throws Exception {73 IMethods methods = Mockito.mock(IMethods.class, AdditionalAnswers.delegatesTo(new MethodsImpl()));74 try {75 byte b = methods.byteObjectReturningMethod();// real method returns null76 Assert.fail();77 } catch (Exception e) {78 assertThat(e.toString()).doesNotContain("org.mockito");79 }80 }81 @Test82 public void instance_of_different_class_can_be_called() {83 List<String> mock = Mockito.mock(List.class, AdditionalAnswers.delegatesTo(new StubbingWithDelegateTest.FakeList<String>()));84 mock.set(1, "1");85 assertThat(mock.get(1).equals("1")).isTrue();86 }87 @Test88 public void method_with_subtype_return_can_be_called() {89 List<String> mock = Mockito.mock(List.class, AdditionalAnswers.delegatesTo(new StubbingWithDelegateTest.FakeList<String>()));90 List<String> subList = mock.subList(0, 0);91 assertThat(subList.isEmpty()).isTrue();92 }93 @Test94 public void calling_missing_method_should_throw_exception() {95 List<String> mock = Mockito.mock(List.class, AdditionalAnswers.delegatesTo(new StubbingWithDelegateTest.FakeList<String>()));96 try {97 mock.isEmpty();98 Assert.fail();99 } catch (MockitoException e) {100 assertThat(e.toString()).contains("Methods called on mock must exist");101 }102 }103 @Test104 public void calling_method_with_wrong_primitive_return_should_throw_exception() {105 List<String> mock = Mockito.mock(List.class, AdditionalAnswers.delegatesTo(new StubbingWithDelegateTest.FakeListWithWrongMethods<String>()));106 try {107 mock.size();108 Assert.fail();109 } catch (MockitoException e) {110 assertThat(e.toString()).contains("Methods called on delegated instance must have compatible return type");111 }112 }113 @Test114 public void calling_method_with_wrong_reference_return_should_throw_exception() {115 List<String> mock = Mockito.mock(List.class, AdditionalAnswers.delegatesTo(new StubbingWithDelegateTest.FakeListWithWrongMethods<String>()));116 try {117 mock.subList(0, 0);118 Assert.fail();119 } catch (MockitoException e) {120 assertThat(e.toString()).contains("Methods called on delegated instance must have compatible return type");121 }122 }123 @Test124 public void exception_should_be_propagated_from_delegate() throws Exception {125 final RuntimeException failure = new RuntimeException("angry-method");126 IMethods methods = Mockito.mock(IMethods.class, AdditionalAnswers.delegatesTo(new MethodsImpl() {127 @Override128 public String simpleMethod() {129 throw failure;130 }131 }));132 try {133 methods.simpleMethod();// delegate throws an exception134 Assert.fail();135 } catch (RuntimeException e) {136 assertThat(e).isEqualTo(failure);137 }138 }139 interface Foo {140 int bar();141 }142 @Test143 public void should_call_anonymous_class_method() throws Throwable {144 StubbingWithDelegateTest.Foo foo = new StubbingWithDelegateTest.Foo() {145 public int bar() {146 return 0;147 }148 };149 StubbingWithDelegateTest.Foo mock = Mockito.mock(StubbingWithDelegateTest.Foo.class);150 Mockito.when(mock.bar()).thenAnswer(AdditionalAnswers.delegatesTo(foo));151 // when152 mock.bar();153 // then no exception is thrown154 }155}...
StubbingWithDelegateTest
Using AI Code Generation
1package org.mockitousage.stubbing;2import static org.mockito.Mockito.*;3import org.junit.Test;4import org.mockito.Mock;5import org.mockito.Mockito;6import org.mockitousage.IMethods;7import org.mockitoutil.TestBase;8public class StubbingWithDelegateTest extends TestBase {9 static class Foo {10 public String bar() {11 return "bar";12 }13 }14 static class FooDelegate implements IMethods {15 public String simpleMethod() {16 return "foo";17 }18 }19 @Mock FooDelegate delegate;20 public void shouldStubWithDelegate() {21 Foo foo = Mockito.mock(Foo.class, withSettings()22 .defaultAnswer(CALLS_REAL_METHODS)23 .useConstructor()24 .defaultAnswer(delegateTo(delegate)));25 when(delegate.simpleMethod()).thenReturn("bar");26 assertEquals("bar", foo.bar());27 assertEquals("bar", delegate.simpleMethod());28 }29}
How to test Spring @Scheduled
Mockito - separately verifying multiple invocations on the same method
How to mock a void static method to throw exception with Powermock?
How to mock void methods with Mockito
Mockito Inject mock into Spy object
Using Multiple ArgumentMatchers on the same mock
How do you mock a JavaFX toolkit initialization?
Mockito - difference between doReturn() and when()
How to implement a builder class using Generics, not annotations?
WebApplicationContext doesn't autowire
If we assume that your job runs in such a small intervals that you really want your test to wait for job to be executed and you just want to test if job is invoked you can use following solution:
Add Awaitility to classpath:
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>3.1.0</version>
<scope>test</scope>
</dependency>
Write test similar to:
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
@SpyBean
private MyTask myTask;
@Test
public void jobRuns() {
await().atMost(Duration.FIVE_SECONDS)
.untilAsserted(() -> verify(myTask, times(1)).work());
}
}
Check out the latest blogs from LambdaTest on this topic:
Enterprise resource planning (ERP) is a form of business process management software—typically a suite of integrated applications—that assists a company in managing its operations, interpreting data, and automating various back-office processes. The introduction of a new ERP system is analogous to the introduction of a new product into the market. If the product is not handled appropriately, it will fail, resulting in significant losses for the business. Most significantly, the employees’ time, effort, and morale would suffer as a result of the procedure.
In general, software testers have a challenging job. Software testing is frequently the final significant activity undertaken prior to actually delivering a product. Since the terms “software” and “late” are nearly synonymous, it is the testers that frequently catch the ire of the whole business as they try to test the software at the end. It is the testers who are under pressure to finish faster and deem the product “release candidate” before they have had enough opportunity to be comfortable. To make matters worse, if bugs are discovered in the product after it has been released, everyone looks to the testers and says, “Why didn’t you spot those bugs?” The testers did not cause the bugs, but they must bear some of the guilt for the bugs that were disclosed.
Sometimes, in our test code, we need to handle actions that apparently could not be done automatically. For example, some mouse actions such as context click, double click, drag and drop, mouse movements, and some special key down and key up actions. These specific actions could be crucial depending on the project context.
I was once asked at a testing summit, “How do you manage a QA team using scrum?” After some consideration, I realized it would make a good article, so here I am. Understand that the idea behind developing software in a scrum environment is for development teams to self-organize.
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!