I was able to implement a non-static setup method with #BeforeAll annotation.
It seems to be working correctly as only gets call once.
I am bit confuse as the documentation for #BeforeAll says the method has to be static. Please explain.
#TestMethodOrder(OrderAnnotation.class)
#SpringJUnitWebConfig(locations = { "classpath:service.xml" })
#TestInstance(Lifecycle.PER_CLASS)
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.TYPE)
#Documented
#Inherited
public class MyTest
{
#BeforeAll
public void setup() throws Exception {...}
}
You simply need to annotate your test class (that contains the #BeforeAll method) with the snippet below and you'll be good to go.
#TestInstance(Lifecycle.PER_CLASS)
If you want use non-static #BeforeAll and #AfterAll methods you should change test instance lifecycle to per_class.
Look there: 2.10. Test Instance Lifecycle
Related
I'm testing a controller that needs a Autowired Service.
I read in many place (example Mockito: How to test my Service with mocking?) I need to do it like this
#RunWith(JUnitPlatform.class)
public class AdminControllerTest {
#Mock
private AdminService service;
#InjectMocks
private AdminController adminController;
#Test
public void registerUser() {
Boolean resultReal = adminController.registerUser();
assertTrue(resultReal);
}
}
But it's fail and I see is because the adminController is null
Instead, if I create the controller like this
AdminController adminController = new AdminController();
It works, but then I can inject the mock.
Maybe I'm forgotten something
Per the documentation for InjectMocks:
MockitoAnnotations.openMocks(this) method has to be called to initialize annotated objects. In above example, openMocks() is called in #Before (JUnit4) method of test's base class. For JUnit3 openMocks() can go to setup() method of a base class. Instead you can also put openMocks() in your JUnit runner (#RunWith) or use the built-in MockitoJUnitRunner.
Thus, either:
call openMocks(this) somewhere before the test is run or
Use #RunWith(MockitoJUnitRunner.class) on the class
(Trying to keep this simple.)
I have a (partial) ByteBuddy recipe like this:
builder
.method(someMatcher())
.intercept(MethodDelegation.to(this.interceptor));
I have an "interceptor" class defined like this:
private static final class Interceptor {
private Interceptor() {
super();
}
#RuntimeType
private final Object doSomething(#This final Proxy<?> proxy,
#SuperCall final Callable<?> callable,
#Origin final String methodSignature) throws Exception {
final Object proxiedInstance = proxy.getProxiedInstance();
// TODO: logic
return callable.call(); // for now
}
}
(The interceptor method needs to be non-static for various reasons not important here.)
When I create an instance of this ByteBuddy-defined class and call a simple public void blork() method on it, I get:
Cannot resolve ambiguous delegation of public void com.foo.TestExplorations$Frob.blork() to net.bytebuddy.implementation.bind.MethodDelegationBinder$MethodBinding$Builder$Build#3d101b05 or net.bytebuddy.implementation.bind.MethodDelegationBinder$MethodBinding$Builder$Build#1a9efd25
How can there be ambiguity when there is only one interceptor? What have I done wrong?
Byte Buddy just adds a method call to the instrumented class which needs to be able to see the target class. If it is private, it is ignored and Byte Buddy searches further up the hierarchy where it finally consideres the methods of Object which are all equally unsuited but therefore an ambiguity exception is thrown instead of an exception that no method could be bound.
I'm working on some automated unit and integration tests for a robot. As you could imagine, a robot has a lot of sensor objects and such that would need mocking during testing.
One of the dependencies is a singleton designed not to be instantiated by anything but itself. As I understood it (I'm new to JMockit), once a class is annotated with #Mocked all of its methods and constructors are mocked. JMockit Documentation:
There are three different mocking annotations we can use when declaring mock fields and parameters: #Mocked, which will mock all methods and constructors on all existing and future instances of a mocked class
However I'm noticing (via the usage of a breakpoint) that the real class' constructor is being called and failing to access a sensor, causing the tests to fail.
Here is the relevant part of the singleton I'm trying to mock. Note that I cannot modify this class:
public class DriverStation() {
// This line in particular is an issue.
private static DriverStation currentInstance = new DriverStation();
public static DriverStation getInstance() {
return DriverStation.instance;
}
private DriverStation() {
// This constructor cannot be called during tests.
}
}
And here is my test code:
public class BlingControllerTest {
#Mocked
private DriverStation station;
#Tested
private BlingController blingController;
/**
* Tests getting the robot's operation period while not in a real match.
*/
#Test
public void testGetOperationPeriodDuringRealMatch(#Mocked DriverStation station) {
new Expectations(DriverStation.class) {{
DriverStation.getInstance();
result = station;
station.isFMSAttached();
result = true;
station.isAutonomous();
returns(true, false);
}};
}
}
Full source also available on GitHub
I should also mention that for some reason calling the singleton's constructor locally during tests isn't a problem, but when the tests are run on travis-ci it is a problem.
Stacktrace from running on travis-ci:
ca.team2706.frc.robot.commands.bling.BlingControllerTest > testGetOperationPeriodDuringRealMatch STANDARD_ERROR
java.io.IOException: wpiHaljni could not be loaded from path or an embedded resource.
attempted to load for platform /linux/x86-64/
at edu.wpi.first.wpiutil.RuntimeLoader.loadLibrary(RuntimeLoader.java:79)
at edu.wpi.first.hal.JNIWrapper.<clinit>(JNIWrapper.java:25)
at edu.wpi.first.wpilibj.DriverStation.<init>(DriverStation.java:194)
at edu.wpi.first.wpilibj.DriverStation.<clinit>(DriverStation.java:132)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:398)
at mockit.internal.state.TestRun.ensureThatClassIsInitialized(TestRun.java:138)
at mockit.internal.expectations.mocking.BaseTypeRedefinition.redefineType(BaseTypeRedefinition.java:65)
at mockit.internal.expectations.mocking.TypeRedefinition.redefineType(TypeRedefinition.java:28)
at mockit.internal.expectations.mocking.FieldTypeRedefinitions.redefineFieldType(FieldTypeRedefinitions.java:78)
at mockit.internal.expectations.mocking.FieldTypeRedefinitions.redefineFieldType(FieldTypeRedefinitions.java:65)
at mockit.internal.expectations.mocking.FieldTypeRedefinitions.redefineFieldTypes(FieldTypeRedefinitions.java:53)
at mockit.internal.expectations.mocking.FieldTypeRedefinitions.<init>(FieldTypeRedefinitions.java:33)
at mockit.integration.TestRunnerDecorator.handleMockFieldsForWholeTestClass(TestRunnerDecorator.java:142)
at mockit.integration.TestRunnerDecorator.updateTestClassState(TestRunnerDecorator.java:40)
Any and all help is appreciated.
I am using JMockit since long.I would like to understand how #Tested works.
Today i was trying to use it within my Test class. What i understand is Whatever class we wants to test we can mark it as #Tested.
One thing which was confusing me about the behaviur of this is when i try to set something in #Before.Below is my query.
My Class for which i want to write Test case
public Class A{
public A(){}
}
Test class
public class ATest {
#Tested
private A a;
#Before
public void setUp(){
a.setSomething();
}
#Test
public void testA(){
}
}
In this case i get NPE. But if i use the same block of code in my test method directly that just works fine.Can anybody help me to understand the behavior of #Tested.
I am using Jmockit version 1.17
I have also checked the post on GitHub as below:
https://github.com/jmockit/jmockit1/issues/168 i just wanted to confirm is it also fixing my problem?
I was able to find what i was looking for
http://jmockit.org/api1x/mockit/Tested.html#availableDuringSetup--
I have a code like this:
public class MyTest extends TestCase {
private MyObject mObject1;
private MyObject mObject2;
...
#Override
public void setUp() throws Exception {
super.setUp();
}
public void testSomething() {
mObject1 = new MyObject();
mObject2 = new MyObject();
}
public void testSomething2() {
// Here I can't access the previously created objects mObject1 and
// mObject2, because they are again null.
// Why is that, if *my* setUp() method doesn't touch them?
}
My guess is that JUnit instantiates the class again every time. Can someone please explain me the workflow?
Thanks.
JUnit will instantiate the class (MyTest) once per test and then execute the methods
setUp()
testXXX()
tearDown()
until it runs all the methods that start with test and don't receive any parameters. So in your example, Junit will instantiate MyTest twice. You can read more about this in the JUnit documentation.
Bear in mind that this is the old way of writing tests. From Junit 4 (I think) the preferred way is to use annotations. You can check the annotations documentation here.
As a side note, NUnit, reuses the instance of the test, so in the same scenario, it would only instantiate MyTest once.
JUnit will instantiate this class once per test method, so only once in the code above, but try it again with two test methods and you will see it instantiated twice. If you want to save some state in fields without having to use statics, take a look at TestNG, which reuses the same instance for all test methods.