Best Mockito code snippet using org.mockito.internal.util.reflection.FieldInitializerTest
Source: FieldInitializerTest.java
...10import org.mockito.BDDMockito;11import org.mockito.InjectMocks;12import org.mockito.Mockito;13import org.mockito.exceptions.base.MockitoException;14public class FieldInitializerTest {15 private FieldInitializerTest.StaticClass alreadyInstantiated = new FieldInitializerTest.StaticClass();16 private FieldInitializerTest.StaticClass noConstructor;17 private FieldInitializerTest.StaticClassWithDefaultConstructor defaultConstructor;18 private FieldInitializerTest.StaticClassWithPrivateDefaultConstructor privateDefaultConstructor;19 private FieldInitializerTest.StaticClassWithoutDefaultConstructor noDefaultConstructor;20 private FieldInitializerTest.StaticClassThrowingExceptionDefaultConstructor throwingExDefaultConstructor;21 private FieldInitializerTest.AbstractStaticClass abstractType;22 private FieldInitializerTest.Interface interfaceType;23 private FieldInitializerTest.InnerClassType innerClassType;24 private FieldInitializerTest.AbstractStaticClass instantiatedAbstractType = new FieldInitializerTest.ConcreteStaticClass();25 private FieldInitializerTest.Interface instantiatedInterfaceType = new FieldInitializerTest.ConcreteStaticClass();26 private FieldInitializerTest.InnerClassType instantiatedInnerClassType = new FieldInitializerTest.InnerClassType();27 @Test28 public void should_keep_same_instance_if_field_initialized() throws Exception {29 final FieldInitializerTest.StaticClass backupInstance = alreadyInstantiated;30 FieldInitializer fieldInitializer = new FieldInitializer(this, field("alreadyInstantiated"));31 FieldInitializationReport report = fieldInitializer.initialize();32 Assert.assertSame(backupInstance, report.fieldInstance());33 Assert.assertFalse(report.fieldWasInitialized());34 Assert.assertFalse(report.fieldWasInitializedUsingContructorArgs());35 }36 @Test37 public void should_instantiate_field_when_type_has_no_constructor() throws Exception {38 FieldInitializer fieldInitializer = new FieldInitializer(this, field("noConstructor"));39 FieldInitializationReport report = fieldInitializer.initialize();40 Assert.assertNotNull(report.fieldInstance());41 Assert.assertTrue(report.fieldWasInitialized());42 Assert.assertFalse(report.fieldWasInitializedUsingContructorArgs());43 }44 @Test45 public void should_instantiate_field_with_default_constructor() throws Exception {46 FieldInitializer fieldInitializer = new FieldInitializer(this, field("defaultConstructor"));47 FieldInitializationReport report = fieldInitializer.initialize();48 Assert.assertNotNull(report.fieldInstance());49 Assert.assertTrue(report.fieldWasInitialized());50 Assert.assertFalse(report.fieldWasInitializedUsingContructorArgs());51 }52 @Test53 public void should_instantiate_field_with_private_default_constructor() throws Exception {54 FieldInitializer fieldInitializer = new FieldInitializer(this, field("privateDefaultConstructor"));55 FieldInitializationReport report = fieldInitializer.initialize();56 Assert.assertNotNull(report.fieldInstance());57 Assert.assertTrue(report.fieldWasInitialized());58 Assert.assertFalse(report.fieldWasInitializedUsingContructorArgs());59 }60 @Test(expected = MockitoException.class)61 public void should_fail_to_instantiate_field_if_no_default_constructor() throws Exception {62 FieldInitializer fieldInitializer = new FieldInitializer(this, field("noDefaultConstructor"));63 fieldInitializer.initialize();64 }65 @Test66 public void should_fail_to_instantiate_field_if_default_constructor_throws_exception() throws Exception {67 FieldInitializer fieldInitializer = new FieldInitializer(this, field("throwingExDefaultConstructor"));68 try {69 fieldInitializer.initialize();70 Assert.fail();71 } catch (MockitoException e) {72 InvocationTargetException ite = ((InvocationTargetException) (e.getCause()));73 Assert.assertTrue(((ite.getTargetException()) instanceof NullPointerException));74 Assert.assertEquals("business logic failed", ite.getTargetException().getMessage());75 }76 }77 @Test(expected = MockitoException.class)78 public void should_fail_for_abstract_field() throws Exception {79 new FieldInitializer(this, field("abstractType"));80 }81 @Test82 public void should_not_fail_if_abstract_field_is_instantiated() throws Exception {83 new FieldInitializer(this, field("instantiatedAbstractType"));84 }85 @Test(expected = MockitoException.class)86 public void should_fail_for_interface_field() throws Exception {87 new FieldInitializer(this, field("interfaceType"));88 }89 @Test90 public void should_not_fail_if_interface_field_is_instantiated() throws Exception {91 new FieldInitializer(this, field("instantiatedInterfaceType"));92 }93 @Test(expected = MockitoException.class)94 public void should_fail_for_local_type_field() throws Exception {95 // when96 class LocalType {}97 class TheTestWithLocalType {98 @InjectMocks99 LocalType field;100 }101 TheTestWithLocalType testWithLocalType = new TheTestWithLocalType();102 // when103 new FieldInitializer(testWithLocalType, testWithLocalType.getClass().getDeclaredField("field"));104 }105 @Test106 public void should_not_fail_if_local_type_field_is_instantiated() throws Exception {107 // when108 class LocalType {}109 class TheTestWithLocalType {110 @InjectMocks111 LocalType field = new LocalType();112 }113 TheTestWithLocalType testWithLocalType = new TheTestWithLocalType();114 // when115 new FieldInitializer(testWithLocalType, testWithLocalType.getClass().getDeclaredField("field"));116 }117 @Test(expected = MockitoException.class)118 public void should_fail_for_inner_class_field() throws Exception {119 new FieldInitializer(this, field("innerClassType"));120 }121 @Test122 public void should_not_fail_if_inner_class_field_is_instantiated() throws Exception {123 new FieldInitializer(this, field("instantiatedInnerClassType"));124 }125 @Test126 public void can_instantiate_class_with_parameterized_constructor() throws Exception {127 FieldInitializer.ConstructorArgumentResolver resolver = BDDMockito.given(Mockito.mock(FieldInitializer.ConstructorArgumentResolver.class).resolveTypeInstances(ArgumentMatchers.any(Class.class))).willReturn(new Object[]{ null }).getMock();128 new FieldInitializer(this, field("noDefaultConstructor"), resolver).initialize();129 Assert.assertNotNull(noDefaultConstructor);130 }131 static class StaticClass {}132 static class StaticClassWithDefaultConstructor {133 StaticClassWithDefaultConstructor() {134 }135 }136 static class StaticClassWithPrivateDefaultConstructor {137 private StaticClassWithPrivateDefaultConstructor() {138 }139 }140 static class StaticClassWithoutDefaultConstructor {141 private StaticClassWithoutDefaultConstructor(String param) {142 }143 }144 static class StaticClassThrowingExceptionDefaultConstructor {145 StaticClassThrowingExceptionDefaultConstructor() throws Exception {146 throw new NullPointerException("business logic failed");147 }148 }149 abstract static class AbstractStaticClass {150 public AbstractStaticClass() {151 }152 }153 interface Interface {}154 static class ConcreteStaticClass extends FieldInitializerTest.AbstractStaticClass implements FieldInitializerTest.Interface {}155 class InnerClassType {156 InnerClassType() {157 }158 }159}...
FieldInitializerTest
Using AI Code Generation
1import org.mockito.internal.util.reflection.FieldInitializer;2import org.mockito.internal.util.reflection.FieldInitializerTest;3public class FieldInitializerTest {4 public void test() throws Exception {5 FieldInitializerTest test = new FieldInitializerTest();6 test.testFinalFieldInitialization();7 }8}9import org.mockito.internal.util.reflection.FieldInitializer;10public class FieldInitializerTest {11 public void test() throws Exception {12 FieldInitializer fieldInitializer = new FieldInitializer();13 fieldInitializer.initializeFields(new Object());14 }15}
FieldInitializerTest
Using AI Code Generation
1public class FieldInitializerTest {2 public void shouldInitializeFieldToNull() throws Exception {3 Field field = FieldInitializerTest.class.getDeclaredField("field");4 Object target = new FieldInitializerTest();5 FieldInitializer.initialize(field, target);6 assertNull(field.get(target));7 }8}9org.mockito.internal.util.reflection.FieldInitializerTest > shouldInitializeFieldToNull() PASSED
FieldInitializerTest
Using AI Code Generation
1public class FieldInitializerTest { 2private static class A { 3private A() {} 4public A(String s) {} 5} 6private static class B { 7private A a; 8} 9private static class C { 10private String s; 11private int i; 12private A a; 13private B b; 14} 15private static class D { 16private String s; 17private int i; 18private A a; 19private B b; 20private C c; 21} 22private static class E { 23private String s; 24private int i; 25private A a; 26private B b; 27private C c; 28private D d; 29} 30private static class F { 31private String s; 32private int i; 33private A a; 34private B b; 35private C c; 36private D d; 37private E e; 38} 39private static class G { 40private String s; 41private int i; 42private A a; 43private B b; 44private C c; 45private D d; 46private E e; 47private F f; 48} 49private static class H { 50private String s; 51private int i; 52private A a; 53private B b; 54private C c; 55private D d; 56private E e; 57private F f; 58private G g; 59} 60private static class I { 61private String s; 62private int i; 63private A a; 64private B b; 65private C c; 66private D d; 67private E e; 68private F f; 69private G g; 70private H h; 71} 72private static class J { 73private String s; 74private int i; 75private A a; 76private B b; 77private C c; 78private D d; 79private E e; 80private F f; 81private G g; 82private H h; 83private I i; 84} 85private static class K { 86private String s; 87private int i; 88private A a; 89private B b; 90private C c; 91private D d; 92private E e; 93private F f; 94private G g; 95private H h; 96private I i; 97private J j; 98} 99private static class L { 100private String s; 101private int i; 102private A a; 103private B b;
How to mock a SecurityContext
How to resolve Unneccessary Stubbing exception
Mocking static private final variable using Powermock?
How to mock a void static method to throw exception with Powermock?
Bad <init> method call from inside of a branch
How to mock new Date() in java using Mockito
Mockito - check if NO method was called on an object(object was not accessed)
Can Mockito verify an argument has certain properties/fields?
Mockito: how to stub void methods to run some code when called
Forming Mockito "grammars"
Disclaimer: I'm not really a Mockito user, but from what I understand, mocking is used for situations where you have injected class dependencies (fields), and you mock those dependencies. In which case you still need to set the field with the mocked object. For example
public class TestClass {
TestService testService;
public void doTest() {
System.out.println(testService.getString());
}
public void setTestService(TestService testService) {
this.testService = testService;
}
}
public class TestService {
public String getString() {
return "Hello world";
}
}
@Test
public void toTest() {
TestService testService = Mockito.mock(TestService.class);
Mockito.when(testService.getString()).thenReturn("Hello Squirrel");
TestClass testClass = new TestClass();
testClass.setTestService(testService);
testClass.doTest();
}
You can see we are setting the the TestService
in the TestClass
with the mocked object. It's not greatest example, as we could simple instantiate TestService
, but it shows, from my understanding, how the mocking should work.
That being said, I don't see how it is possible to do this with the AuthorizationRequestFilter
, as it's handled by the test container, and we are not instantiating it for a unit test. Even if we were, it would seem intrusive (and redundant) to add a SecurityContext
field.
So without a full integration test, where we are starting the server, and using the server's authentication capabilities, it will be difficult to handle the SecurityContext
per this use case, as the SecurityContext
is created by the container, taking information from the underlying servlet containers authentication mechanism.
One way you can achieve this though (which IMO doesn't seem very elegant - but works), without a full integration test, is to create a a filter which performs before your AuthorizationRequestFilter
, and set the SecurityContext
from there. Testing aside, this is actually pretty common in cases where we need to implement outr own custom authentication mechanism.
An example of how you might do this for your unit test, might be something like:
public class UrlerResourceTest extends JerseyTest {
...
@Override
public Application configure() {
return new ResourceConfig(FooResource.class)
.register(AuthorizationRequestFilter.class)
.register(AuthenticationFilter.class);
}
@Provider
@Priority(Priorities.AUTHENTICATION)
public static class AuthenticationFilter implements ContainerRequestFilter {
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
requestContext.setSecurityContext(new SecurityContext() {
@Override
public Principal getUserPrincipal() {
return new Principal() {
@Override
public String getName() {
return "Stackoverflow";
}
};
}
@Override
public boolean isUserInRole(String string) {
return "privileged".equals(string);
}
@Override
public boolean isSecure() { return true; }
@Override
public String getAuthenticationScheme() { return "BASIC"; }
});
}
}
...
}
This filter will perform before the AuthorizationRequestFilter
because of the @Priority
annotation. We've set it to Priorities.AUTHENTICATION
which will before before any other filter without such annotation. (See Priorities API and Priorities with Jersey. Also the SecurityContext
will be passed along between filters and also be injected into your resource class.
As I said, I don't think this is very elegant to have to create another filter, but it works for this purpose. Also I am not too familiar with the Jersey Test Framework, as I'm still beginning with it, but there are many configuration options for deployment within a servlet context. I don't know if we can configure the needed authentication mechanism for this case, but it might be something worth looking into.
Edit: In the beginning I explained about setting the field for the test object, but we can also pass the mocked object to a method. For example we could mock the ContainterRequestContext
in the filter
method, and call filter
ourselves, passing the mocked ContainerRequestContext
. But this is only useful when we are actually unit testing the filter class and instantiating it ourselves, which is not the case here.
Check out the latest blogs from LambdaTest on this topic:
The QA testing career includes following an often long, winding road filled with fun, chaos, challenges, and complexity. Financially, the spectrum is broad and influenced by location, company type, company size, and the QA tester’s experience level. QA testing is a profitable, enjoyable, and thriving career choice.
Testing is a critical step in any web application development process. However, it can be an overwhelming task if you don’t have the right tools and expertise. A large percentage of websites still launch with errors that frustrate users and negatively affect the overall success of the site. When a website faces failure after launch, it costs time and money to fix.
Agile software development stems from a philosophy that being agile means creating and responding to change swiftly. Agile means having the ability to adapt and respond to change without dissolving into chaos. Being Agile involves teamwork built on diverse capabilities, skills, and talents. Team members include both the business and software development sides working together to produce working software that meets or exceeds customer expectations continuously.
When most firms employed a waterfall development model, it was widely joked about in the industry that Google kept its products in beta forever. Google has been a pioneer in making the case for in-production testing. Traditionally, before a build could go live, a tester was responsible for testing all scenarios, both defined and extempore, in a testing environment. However, this concept is evolving on multiple fronts today. For example, the tester is no longer testing alone. Developers, designers, build engineers, other stakeholders, and end users, both inside and outside the product team, are testing the product and providing feedback.
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!!