Is there any reason why everybody uses #Before instead of #BeforeClass with initMocks? In my case I have only one method call in setup method and that is MockitoAnnotations.initMocks. #BeforeClass is even faster.
#BeforeClass, as the name suggest is run after class is loaded and no object exist. So all variable which you initialize need to be static. So, if you want to reuse this static variable in all testcases, as base setup input data, then you can do ahead with using #BeforeClass.
#Before is useful, then you want to reset the data before each test case gets called, so you are sure, anyone changing the input base data, does not impact the with what the next test is called.
coming to initmock, you can do via #Mock, #InjectMocks and using #RunWith(MockitoJUnitRunner.class)
#RunWith(MockitoJUnitRunner.class)
public class SampleTest {
#InjectMocks
private ClassA classA;
#Mock
private ClassB classB
// #BeforeClass and other test methods
}
In above code,
1. Instance of ClassA will be created
2. Mock object of ClassB will be created
3. classB will be injected in ClassA object created in step 1
Related
Here is my test class
#SpringBootTest
#ActiveProfiles("test")
public MyTest {
...
#Before
public void init() {
System.out.println(":::: --- start init() ---");
...
}
...
}
Strange enough, the init() won't run for some reason. If I change the #Before to #BeforeAll and the method to static, the init() will run. A problem is that those data set up code doesn't run inside a static method and I can't change all of them to run inside a static block. For now, I have the following code in each test method to overcome the issue
if(list.size() == 0)
init();
I am wondering why the #Before won't run. Any advice?
In JUnit 5, #BeforeEach and #BeforeAll annotations are the equivalents for #Before and #BeforeClass in JUnit 4.
#Before is a JUnit 4 annotation, while #BeforeAll is a JUnit 5 annotation. You can also see this from the imports org.junit.Before and org.junit.jupiter.api.BeforeAll.
Also, the code marked #BeforeEach is executed before each test, while #BeforeAll runs once before the entire test fixture.
To be able to run #BeforeAll on a non-static method you can change the lifecycle of the the test instance with:
#TestInstance(TestInstance.Lifecycle.PER_CLASS)
You have to be careful though, since the test class instance is now only created once, and not once per test method. If your test methods rely on state stored in instance variables, you may now need to manually reset the state in #BeforeEach or #AfterEach lifecycle methods.
I'm trying to create tests for my spring-cloud-stream project. I've created my own BizSyncProcessor interface instead of using the default Processor, which seems to be in all the documentation. I've done this kind of project before with tests, but can't remember if I used mockito at the same time, so I'm wondering if that's the issue, because I'm doing #RunWith(MockitoJUnitRunner.class) instead of #RunWith(SpringRunner).
I also had similar problems when building the actual app, before I included the rabbit implementation as a dependency in maven.
IntelliJ flags an error on the #Autowired BizSyncProcessor saying 'no Beans of type 'BizSyncProcessor' could be found. However I'm able to run the test, so it compiles, but then bizSyncProcessor is null when running the test.
I'm including mockito because the handler that listens for the message makes a call to another service (the SFISClient), so I'm mocking out that call.
Here's my test:
#RunWith(MockitoJUnitRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
#EnableAutoConfiguration
#Configuration
#EnableBinding(BizSyncProcessor.class)
public class UpdatedBusinessHandlerTest {
#Autowired
private BizSyncProcessor bizSyncProcessor;
#Autowired
private MessageCollector messageCollector;
#Mock
SFISClient sfisClient;
#InjectMocks
UpdatedBusinessHandler updatedBusinessHandler;
#Test
public void testWiring() throws Exception {
UpdatedBusinessAlert updatedBusinessAlert = new UpdatedBusinessAlert();
updatedBusinessAlert.setBusinessId(UUID.randomUUID());
Message<UpdatedBusinessAlert> updatedBusinessAlertMessage = MessageBuilder.withPayload(updatedBusinessAlert).build();
bizSyncProcessor.writeUpdatedBusinessIds().send(updatedBusinessAlertMessage);
Message<BusinessFlooringSummary> businessFlooringSummaryMessage = (Message<BusinessFlooringSummary>) messageCollector.forChannel(bizSyncProcessor.writeFlooringSummaries()).poll();
BusinessFlooringSummary businessFlooringSummary = businessFlooringSummaryMessage.getPayload();
assertNotNull(businessFlooringSummary);
}
}
The #SpringBootTest and everything Spring-based are not going to work in your case because you don't use #RunWith(SpringRunner). There is just nothing what can trigget those Spring hooks.
On the other hand there is no reason to use a MockitoJUnitRunner. You simply can rely on the #MockBean instead for your SFISClient: https://docs.spring.io/spring-boot/docs/2.1.1.RELEASE/reference/htmlsingle/#boot-features-testing-spring-boot-applications-mocking-beans
I'm new to groovy...
I've made a class. Within this class, I'd like to call an external method : LOG.error, but somehow, groovy is complaining about the method not being part of the class... how should I call that external method ?
class GAPI{
private myvar
public getResult(){
this.myvar="blabla"
LOG.error("test")
}
}
Groovy provides #Slf4j annotation that can add log field to your class, e.g.
#Slf4j
class GAPI{
private myvar
public getResult(){
this.myvar="blabla"
log.error("test")
}
}
Alternatively you can use #Log annotation that adds log field that uses java.util.logging.Logger instead of one provided with Slf4j. However in this case you have to be aware that java.util.logging.Logger uses different API, so there is no log.error() method.
In your example Groovy throws MissingPropertyException, because LOG is not defined in your class. If there is a class LOG with static method error you will have to import this class. But most probably you should just create LOG field (with annotation or manually) and call it to be most explicit (otherwise your code gets unreadable).
I am writing junit test to test BaseClass method. The method uses super class members.
The BaseClass constructor invokes super(arg1, arg2).
In the super(arg1, arg2) constructor there is a dependency injector setting a private member
of the super class.
When I am running the test, since the dependency is not set, the super() is throwing an
exception. I want to mock only that statement in the super() which is setting the private member with dependency injection. How to do with mockito ?
Field injection is always a problem for testing. So whenever you have the choice, choose constructor injection instead.
You could start the dependency injector and make it inject a mock instead of a real class. Solutions would depend on the DI framework that you use actually (guice, cdi, ...) For guice you could use jukito, for cdi Arquillian for example. But it slows down the test execution and adds complexity to your test class.
As a alternative you could reflect the private field on an instance of you test class an simply set a mock. Something like:
instance = new TestObject();
Field injected = TestObject.class.getDeclaredField("injected");
injected.setAccessible(true);
injected.set(instance, mock(InjectedType.class));
while TestObject is the class that you want to test, injected the private field where something is injected an InjectedType the type of that private field.
I'm studying how Rhino.Mocks works and trying to understand how can I set manually a value in a class Property.
I have seen a sample in internet where you have only desired Property as argument of Expect.Call(), instead of using a method.
MockRepository mocks = new MockRepository();
Person p = mocks.StrictMock<Person>();
Expect.Call(p.FirstName).Return("John");
Person is a class such as:
public class Person
{
public string FirstName {get;set;}
}
I always receive the error:
Invalid call, the last call has been
used or no call has been made (make
sure that you are calling a virtual
(C#) / Overridable (VB) method).
Am I missing something? Is it possible to set manually class Properties and evaluate them to see if getters and setters are working fine?
As with any mocking framework, Rhino Mocks can only mock interfaces or classes that defines virtual methods and properties.
That's because when implementing a class, Rhino creates a derived class from the one you specify, replacing every virtual (or Overridable in VB) method with a stub implementation that uses an interceptor to handle the call.
When you specify a non virtual method, Rhino can't create a wrapper.
That is also true tor sealed (NonInheritable in VB) classes.
So for your class to work, you should implement the property as such:
public class Person
{
public virtual string FirstName { get; set; }
}
This way Rhino can override the poperty accordingly.