How to test a constructor call in JMockit for the following piece of code - jmockit

public class HuronClassloader extends URLClassLoader {
public HuronClassloader(Logger logger) {
super(new URL[0]);
this.logger = logger;
}
public void doLogic() throws ClasspathFormattingException {
// logic go heer
}
// How to test the doLogic method using JMockit?

You can try as follows; #Injectable will automatically inject the mock Logger object to the constructor when initializing your tested class.
import mockit.Injectable;
import mockit.Tested;
...
#Tested
HuronClassloader loader;
#Injectable
Logger logger;
#Test
public void testSomeMethod() {
//Optionally you can set expectation on your mock
new Expectations() {{
logger.someMethod(); result = ...;
}};
loader.doLogic();
}

Related

Using and extending JOOQ generated DAOs with injected DataSource?

I'm new to JOOQ... The following code seems to work in WildFly 22 but I'm not sure if that is the best way to do things. What is the preferred way to inject WF DataSource to JOOQ DAOs (my extended ones)? Is there a way to avoid doing the ".get()." in the service below and just leave #Resource(...) etc. connection related for the MyCompanyDAO to handle internally?
In other words: companyDAO.get().fetchOneById(id) vs. companyDAO.fetchOneById(id)
#Stateless
public class CompanyService extends DefaultCompanyService {
#Inject
private MyCompanyDAO companyDAO;
public Company find(Integer id) {
return companyDAO.get().fetchOneById(id);
}
}
#Stateless
public class MyCompanyDAO extends CompanyDao {
#Inject
private MyConnectionProvider cp;
public CompanyDAO get() { // since cannot use #Resource in dao constructor
this.configuration().set(cp).set(SQLDialect.POSTGRES);
return this;
}
// custom code here
}
public class CompanyDao extends DAOImpl<CompanyRecord, tables.pojos.Company, Integer> {
// jooq generated code here
}
#Stateless
#LocalBean
public class MyConnectionProvider implements ConnectionProvider {
#Resource(lookup = "java:/MyDS")
private DataSource dataSource;
#Override
public Connection acquire() throws DataAccessException {
try {
return dataSource.getConnection();
} catch (SQLException e) {
throw new DataAccessException("Could not acquire connection.", e);
}
}
#Override
public void release(Connection connection) throws DataAccessException {
try {
connection.close();
} catch (SQLException e) {
throw new DataAccessException("Could not release connection.", e);
}
}
}
Put initialization logic of MyCompanyDAO inside a #PostConstruct method.
#PostConstruct
public void init() {
this.configuration().set(cp).set(SQLDialect.POSTGRES);
}
This way, you don't need to call get:
#Inject
private MyCompanyDAO companyDAO;
public Company find(Integer id) {
return companyDAO.fetchOneById(id);
}
How about using constructor injection instead? The generated DAO classes offer a constructor that accepts a Configuration precisely for that:
#Stateless
public class MyCompanyDAO extends CompanyDao {
#Inject
public MyCompanyDAO (Configuration configuration) {
super(configuration);
}
}
If for some reason you cannot inject the entire configuration (which I'd recommend), you could still inject the ConnectionProvider:
#Stateless
public class MyCompanyDAO extends CompanyDao {
#Inject
public MyCompanyDAO (MyConnectionProvider cp) {
super(DSL.using(cp, SQLDialect.POSTGRES));
}
}

How to mock protected final method of base class using jmockit

public class Dao1 extends GenericDao{
}
public class Dao2 extends Dao1{
}
public class GenericDao(){
protected final Session getCurrentSession() {
LOG.debug("getting current Session");
return sessionFactory.getCurrentSession();
}
}
I am testing methods in Dao2 and wants to mock getCurrentSession method from GenericDao.
I tried to mock it using
new MockUp<GenericDao>() {
#Mock
protected Session getCurrentSession() {
return session;
}
};
}
I am getting following exception at line new MockUp<GenericDao>():
java.lang.NoSuchMethodError: mockit.internal.startup.AgentLoader: method <init>()V not found
at mockit.internal.startup.Startup.verifyInitialization(Startup.java:172)
at mockit.MockUp.<clinit>(MockUp.java:94)

AxonFramework: How to test #EventHandler

I have this component which integrates with other services through a RabbitMQ queue:
#Component
#ProcessingGroup("amqpProcessor")
public class ExternalEventsHandler {
#EventHandler
public void on(SomeOtherServiceEvent event) {
// Dispatches some command
}
}
How should I test this?
#Test
public void shouldReactToSomeOtherServiceEvent() {
//TODO
}
The best way is just to instantiate or inject your event handler class in the unit test, instantiate a test event, and simply call the method. Something like this:
#Mock
private FooRepository fooRepository;
private FooEventHandler fooEventHandler;
#Before
public void before() {
fooEventHandler = new FooEventHandler(fooRepository);
}
#Test
public void createFoo() {
fooEventHandler.createFoo(new FooCreatedEvent("fooId");
ArgumentCaptor<Foo> argument = ArgumentCaptor.forClass(Foo.class);
verify(fooRepository, times(1)).save(argument.capture());
assertTrue(argument.getValue().getId(), "fooId"));
}

How to Mock java.util.logging

I am new to jMockit and run into trouble when trying to test classes which have a instance of java.util.logger injected.
I've tried a number of ideas how to do this,,
Can anyone show how to me how to do it
public class underTest {
#Inject
Logger logger;
#Inject Service service;
public void doSomeThing()
{
logger.info("Invoking Service... ");
service.serve();
};
}
public class TestClass
{
#Tested underTest tested;
#Test
public void howToTest()
{
.
,
.
.
tested.doSomeThing();
}
}
There would be several ways to test it. I HIGHLY recommend you to read JMockit's Tutorial.
In your case this should work:
#RunWith(JMockit.class)
public class TestFoo {
#Injectable
Logger logger;
#Injectable
Service service;
#Tested
private UnderTest underTest;
#Test
public void howToTest(){
underTest.doSomeThing();
new Verifications(){{
service.serve();
logger.info(anyString);
}};
}
}

Why is there a NPE on #Injectable class

I have a class(looks something like this) I'm trying to test.
#Component
#Path("/user")
#Produces(MediaType.APPLICATION_JSON)
public class UserResource extends BaseResource {
#Autowired UserService userService;
#POST
#Path("register")
public User registerUser(User user){
...
User registeredUser = userService.register(user);
...
return registeredUser;
}
}
The test looks like this.
public class UserResourceTest {
#Tested UserResource userResource;
#Injectable UserService userService;
#Mocked BaseResource baseResource;
#Test
public void registerShouldDoSomething(){
User user = new User();
final User registerResult = new User();
...
new NonStrictExpectations() {{
userService.register((User)any); result = registerResult;
}};
userResource.registerUser(user);
...
}
}
For some reason in the tested class, userService is null and throwing a NPE when register is called on it (UserService is a class not interface/abstract btw). I'm wondering if perhaps some of the annotations(javax or Spring) may be clashing with JMockit or something(Although I've tried removing them)?
I've tried switching the injectable to just #Mocked, and I've tried removing it and having it be a #Mocked test method param. Nothing seems to be solving the NPE.
I had the same issue, the problem was mixing Spring annotations - Autowired with Java Resource. If you mix them only Java will be injected.
For more details please take a look at:
mockit.internal.expectations.injection.InjectionPoint
mockit.internal.expectations.injection.FieldInjection
especially discardFieldsNotAnnotatedWithJavaxInjectIfAtLeastOneIsAnnotated method.
This is a dirty solution to the problem:
package mockit.internal.expectations.injection;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
public class DirtyHack {
static {
try {
setFinalStatic(InjectionPoint.class.getDeclaredField("WITH_INJECTION_API_IN_CLASSPATH"), false);
} catch (Exception e) {
e.printStackTrace();
}
}
static void setFinalStatic(Field field, Object newValue) throws Exception {
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, newValue);
}
}
Then your test need to for example extends this class.
I ended up using reflection to manually set the #Injectable fields in the #Tested class
public class UserResourceTest {
#Tested UserResource userResource;
#Injectable UserService userService;
#Mocked BaseResource baseResource;
#Test
public void registerShouldDoSomething(){
Deencapsulation.setField(userResource,userService); //This line
User user = new User();
final User registerResult = new User();
...
new NonStrictExpectations() {{
userService.register((User)any); result = registerResult;
}};
userResource.registerUser(user);
...
}
}
Still not sure what the bug is, but this works for me