/**
* Copyright (C) 2022 by Martin Robillard. See https://codesample.info/about.html
*/
package e2.chapter5;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.lang.reflect.Field;
import org.junit.jupiter.api.Test;
public class TestGameModel {
static class implements PlayingStrategy {
private boolean aExecuted = false;
public boolean hasExecuted() {
return aExecuted;
}
@Override
public Move computeNextMove(GameModelView pModelView) {
aExecuted = true;
return new NullMove();
}
}
@Test
void testTryToAutoPlay() {
try {
Field strategyField = GameModel.class.getDeclaredField("aPlayingStrategy");
strategyField.setAccessible(true);
StubStrategy strategy = new StubStrategy();
GameModel model = GameModel.instance();
strategyField.set(model, strategy);
model.tryToAutoPlay();
assertTrue(strategy.hasExecuted());
}
catch( ReflectiveOperationException e ) {
fail();
}
}
}
This code uses metaprogramming to inject a stub into the object under test.
This code uses metaprogramming to inject a stub into the object under test.
This code is a test stub. Its purpose is to allow its client
to check that method computeNextMove
was actually executed, without
having to deal with the complexity of the execution of an actual
(non-stub) playing strategy object.
Chapter 5, insight #12
To isolate the behavior of stateful objects that refer to many other objects, consider using stubs to abstract the behavior of the component objects
This code is a test stub. Its purpose is to allow its client
to check that method computeNextMove
was actually executed, without
having to deal with the complexity of the execution of an actual
(non-stub) playing strategy object.
Chapter 5, insight #12
To isolate the behavior of stateful objects that refer to many other objects, consider using stubs to abstract the behavior of the component objects
@Test
is used to signal that the annotated method is a test method.
@Test
is used to signal that the annotated method is a test method.
@Test
methods must not be private
or static
and must not return a value.
@Test
methods may optionally declare parameters to be resolved by ParameterResolvers
.
@Test
may also be used as a meta-annotation in order to create a custom composed annotation that inherits the semantics of @Test
.
@Test
methods are inherited from superclasses as long as they are not overridden according to the visibility rules of the Java language. Similarly, @Test
methods declared as interface default methods are inherited as long as they are not overridden.
By default, test methods will be ordered using an algorithm that is deterministic but intentionally nonobvious. This ensures that subsequent runs of a test suite execute test methods in the same order, thereby allowing for repeatable builds. In this context, a test method is any instance method that is directly annotated or meta-annotated with @Test
, @RepeatedTest
, @ParameterizedTest
, @TestFactory
, or @TestTemplate
.
Although true unit tests typically should not rely on the order in which they are executed, there are times when it is necessary to enforce a specific test method execution order — for example, when writing integration tests or functional tests where the sequence of the tests is important, especially in conjunction with @TestInstance(Lifecycle.PER_CLASS)
.
To control the order in which test methods are executed, annotate your test class or test interface with @TestMethodOrder
and specify the desired MethodOrderer
implementation.
Field
object that reflects the specified declared field of the class or interface represented by this Class
object. The name
parameter is a String
that specifies the simple name of the desired field.
Field
object that reflects the specified declared field of the class or interface represented by this Class
object. The name
parameter is a String
that specifies the simple name of the desired field.
If this Class
object represents an array type, then this method does not find the length
field of the array type.
name
- the name of the field
Field
object for the specified field in this class
NoSuchFieldException
- if a field with the specified name is not found.
NullPointerException
- if name
is null
SecurityException
- If a security manager, s, is present and any of the following conditions is met:
s.checkPermission
method with RuntimePermission("accessDeclaredMembers")
denies access to the declared field s.checkPackageAccess()
denies access to the package of this class Field
provides information about, and dynamic access to, a single field of a class or an interface. The reflected field may be a class (static) field or an instance field.
Field
provides information about, and dynamic access to, a single field of a class or an interface. The reflected field may be a class (static) field or an instance field.
A Field
permits widening conversions to occur during a get or set access operation, but throws an IllegalArgumentException
if a narrowing conversion would occur.
accessible
flag for this reflected object to the indicated boolean value. A value of true
indicates that the reflected object should suppress checks for Java language access control when it is used. A value of false
indicates that the reflected object should enforce checks for Java language access control when it is used, with the variation noted in the class description.
accessible
flag for this reflected object to the indicated boolean value. A value of true
indicates that the reflected object should suppress checks for Java language access control when it is used. A value of false
indicates that the reflected object should enforce checks for Java language access control when it is used, with the variation noted in the class description.
This method may be used by a caller in class C
to enable access to a member
of declaring class
D
if any of the following hold:
C
and D
are in the same module. public
and D
is public
in a package that the module containing D
exports
to at least the module containing C
. protected
static
, D
is public
in a package that the module containing D
exports to at least the module containing C
, and C
is a subclass of D
. D
is in a package that the module containing D
opens
to at least the module containing C
. All packages in unnamed and open modules are open to all modules and so this method always succeeds when D
is in an unnamed or open module. This method may be used by JNI code with no caller class on the stack to enable access to a member
of declaring class
D
if and only if:
public
and D
is public
in a package that the module containing D
exports
unconditionally. This method cannot be used to enable access to private members, members with default (package) access, protected instance members, or protected constructors when the declaring class is in a different module to the caller and the package containing the declaring class is not open to the caller's module.
This method cannot be used to enable write access to a non-modifiable final field. The following fields are non-modifiable:
The accessible
flag when true
suppresses Java language access control checks to only enable read access to these non-modifiable final fields.
If there is a security manager, its checkPermission
method is first called with a ReflectPermission("suppressAccessChecks")
permission.
setAccessible
in class AccessibleObject
flag
- the new value for the accessible
flag
InaccessibleObjectException
- if access cannot be enabled
SecurityException
- if the request is denied by the security manager
Field
object on the specified object argument to the specified new value. The new value is automatically unwrapped if the underlying field has a primitive type.
Field
object on the specified object argument to the specified new value. The new value is automatically unwrapped if the underlying field has a primitive type.
The operation proceeds as follows:
If the underlying field is static, the obj
argument is ignored; it may be null.
Otherwise the underlying field is an instance field. If the specified object argument is null, the method throws a NullPointerException
. If the specified object argument is not an instance of the class or interface declaring the underlying field, the method throws an IllegalArgumentException
.
If this Field
object is enforcing Java language access control, and the underlying field is inaccessible, the method throws an IllegalAccessException
.
If the underlying field is final, this Field
object has write access if and only if the following conditions are met:
setAccessible(true)
has succeeded for this Field
object;IllegalAccessException
.
Setting a final field in this way is meaningful only during deserialization or reconstruction of instances of classes with blank final fields, before they are made available for access by other parts of a program. Use in any other context may have unpredictable effects, including cases in which other parts of a program continue to use the original value of this field.
If the underlying field is of a primitive type, an unwrapping conversion is attempted to convert the new value to a value of a primitive type. If this attempt fails, the method throws an IllegalArgumentException
.
If, after possible unwrapping, the new value cannot be converted to the type of the underlying field by an identity or widening conversion, the method throws an IllegalArgumentException
.
If the underlying field is static, the class that declared the field is initialized if it has not already been initialized.
The field is set to the possibly unwrapped and widened new value.
If the field is hidden in the type of obj
, the field's value is set according to the preceding rules.
obj
- the object whose field should be modified
value
- the new value for the field of obj
being modified
IllegalAccessException
- if this Field
object is enforcing Java language access control and the underlying field is inaccessible or final; or if this Field
object has no write access.
IllegalArgumentException
- if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof), or if an unwrapping conversion fails.
NullPointerException
- if the specified object is null and the field is an instance field.
ExceptionInInitializerError
- if the initialization provoked by this method fails.
Although failing with an explicit failure message is recommended, this method may be useful when maintaining legacy code.
See Javadoc for fail(String)
for an explanation of this method's generic return type V
.