PowerMockito failing to create an instance of a class which has anonymous block - powermockito

I just converted our application code into simple classes to express the problem concisely. Our use case contains a class which internally uses some helper classes with static methods which needs to be mocked. So, planned to use PowerMockito. No issues with this part, however we have one class where we have an anonymous block inside one of the methods. When we try to create an instance of this class, PowerMockito fails with a very vague error. Tried spending few hours to resolve the issue without any luck.
public abstract class AbstractClass {
public abstract void methodOne(String arg);
public void methodTwo()
{
System.out.println("In method two");
}
}
public class StaticMethod {
public static String someStaticMethod()
{
System.out.println("in static method");
return "static";
}
}
public class AbstractClassCaller {
public AbstractClassCaller()
{
StaticMethod.someStaticMethod();
// The following piece of code is the problematic block
AbstractClass abstractClassInstance = new AbstractClass(){
public void methodOne(String methodArg)
{
System.out.println("In Method One");
}
};
}
}
#Test
#PrepareForTest({AbstractClassCaller.class,StaticMethod.class})
public class AbstractClassCallerTest {
#Test
public void test() throws Exception
{
PowerMockito.mockStatic(StaticMethod.class);
PowerMockito.when(StaticMethod.someStaticMethod()).thenReturn(
"PowerStatic");
// This is the code which triggers the exception
AbstractClassCaller instance = new AbstractClassCaller();
}
#ObjectFactory
public IObjectFactory getObjectFactory() {
return new org.powermock.modules.testng.PowerMockObjectFactory();
}
}
The above junit class fails with the following exception:
org.powermock.reflect.exceptions.ConstructorNotFoundException: Failed to lookup constructor with parameter types [ com.oracle.oal.seaas.AbstractClassCaller ] in class com.oracle.oal.seaas.AbstractClassCaller$1.
at com.oracle.oal.seaas.AbstractClassCallerTest.test(AbstractClassCallerTest.java:21)
Caused by: java.lang.NoSuchMethodException: com.oracle.oal.seaas.AbstractClassCaller$1.<init>(com.oracle.oal.seaas.AbstractClassCaller)
at com.oracle.oal.seaas.AbstractClassCallerTest.test(AbstractClassCallerTest.java:21)
// the following anonymous block in AbstractClassCaller is causing the issue:
AbstractClass abstractClassInstance = new AbstractClass(){
public void methodOne(String methodArg)
{
System.out.println("In Method One");
}
};
Any ideas on how to fix this issue?

Related

How to show exception status code on error page use springmvc

Custom exception
public class JsonException extends RuntimeException{
private int code;
public JsonException() {
}
public JsonException(String message) {
super(message);
}
public JsonException(int code, String message) {
super(message);
this.code = code;
}
public JsonException(Throwable cause) {
super(cause);
}
public JsonException(String message, Throwable cause) {
super(message, cause);
}
}
Rest URI
#RestController
#RequestMapping("/api")
public class Rests {
#GetMapping("/e")
public Boolean exceptionCode() {
throw new JsonException(401, "test");
}}
Request for '/api/e', the error page write status 500.The problem is how to make the message is 'status=401,Type =test',
You are directly throwing exception in controller that why you got internal server error.
If you want return any specific reason then you have to construct object need to set the reason by exception.getMessage() and set the status code.

Corda tutorial's contract test ledget method error

I'm trying to implement a Contract test on Java as described there.
I paste the first test's code in my project and changed import static net.corda.testing.NodeTestUtils.ledger; to import static net.corda.testing.node.NodeTestUtils.ledger;
package com.template;
import org.junit.Test;
import static net.corda.testing.node.NodeTestUtils.ledger;
public class CommercialPaperTest {
#Test
public void emptyLedger() {
ledger(l -> {
return null;
});
}
}
And I see that ledger method has an absolutely different signature, so Java says that it cannot resolve method ledger(<lambda expression>).
What am I doing wrong?
There is an error on that page. The first argument to ledger should be a MockServices instance.
For example, we might write:
public class CommercialPaperTest {
private static final TestIdentity megaCorp = new TestIdentity(new CordaX500Name("MegaCorp", "London", "GB"));
private MockServices ledgerServices;
#Before
public void setUp() {
ledgerServices = new MockServices(
singletonList("net.corda.finance.contracts"),
megaCorp,
makeTestIdentityService(megaCorp.getIdentity())
);
}
#Test
public void emptyLedger() {
ledger(ledgerServices, l -> {
return null;
});
}
}

Mockito unable to mock ThreadLocalRandom

I am trying to mock ThreadLocalRandom in my JUnit test.
#RunWith(PowerMockRunner.class)
public class SomeTest {
List<Game> games;
#Before
public void setUp() throws Exception {
mockStatic(ThreadLocalRandom.class);
when(ThreadLocalRandom.current()).thenReturn(any(ThreadLocalRandom.class));
when(ThreadLocalRandom.current().nextInt(any(Integer.class))).thenReturn(1);
games = Arrays.asList(new Game1(), new Game2());
}
#PrepareForTest({ ThreadLocalRandom.class })
#Test
public void someTestName() {
assertTrue(new Game(games).winner().equals(new Game1()));
}
}
While running the test I am getting error like,
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
0 matchers expected, 1 recorded:
Any input how to solve this?
public class Toss {
private final List<Game> games;
public Toss(List<Game> games) {
this.games = games;
}
public Game winner() {
return games.get(ThreadLocalRandom.current().nextInt(games.size()));
}
}
Any input what am I missing here?
The line
when(ThreadLocalRandom.current()).thenReturn(any(ThreadLocalRandom.class));
makes no sense. You can't tell Mockito (or PowerMock) to return just any old ThreadLocalRandom that it likes. You need to tell it which object to return. So instantiate ThreadLocalRandom and use the object that you create after thenReturn.

Where can I put Logging mechanism on my code

I am using asp.net mvc applicaiton and I am new about cross cutting concers. So I need to know where can I use my logger code following example.
I have an interface that logs erros. I am implementing this interface on my code.
public interface ILogger { void Log(Exception exception); }
So I have Controller, ProductService, ProductRepository classes.
public interface ProductController: ApiController{
public IHttpActionResult Get(){
try {
productService.GetProducts();
}catch(Exception e){
logger.Log(e); // 1-Should I use logging in here?
}
}
}
Product service;
public class ProductService{
public IEnumerable<Product> GetProducts(){
try {
productRepository.GetAll();
}catch(Exception e){
logger.Log(e); // 2-Should I use logging in here?
}
}
}
In repository.
public class ProductRepository{
public IEnumerable<Product> GetAll(){
try {
}catch(Exception e){
logger.Log(e); // 3-Should I use logging in here?
}
}
}
I could not determine where can I use logging code. Or add logging in everywhere.
You can implement custom exception filter.
public class LogExceptionAttribute : ExceptionFilterAttribute
{
public ILogger logger { get; set; }
public LogExceptionAttribute(ILogger logger)
{
this.logger = logger;
}
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
var exception = actionExecutedContext.Exception;
logger.Log(actionExecutedContext.Exception);
// You could also send client a message about exception.
actionExecutedContext.Response =
actionExecutedContext.Request.CreateResponse(HttpStatusCode.InternalServerError, exception.Message);
}
}
Then register it on global level.
GlobalConfiguration.Configuration.Filters.Add(new LogExceptionAttribute(Logger));
This filter would be called for any unhandled exception thrown from controller method.

Why addClickListener is not reconized? [duplicate]

My Eclipse worked fine a couple of days ago before a Windows update. Now I get error messages whenever I'm trying to do anything in Eclipse. Just a simple program as this will display a bunch of error messages:
package lab6;
public class Hellomsg {
System.out.println("Hello.");
}
These are the errors I receive on the same line as I have my
"System.out.println":
"Multiple markers at this line
- Syntax error, insert ")" to complete MethodDeclaration
- Syntax error on token ".", # expected after this token
- Syntax error, insert "Identifier (" to complete MethodHeaderName"
You can't just have statements floating in the middle of classes in Java. You either need to put them in methods:
package lab6;
public class Hellomsg {
public void myMethod() {
System.out.println("Hello.");
}
}
Or in static blocks:
package lab6;
public class Hellomsg {
static {
System.out.println("Hello.");
}
}
You can't have statements outside of initializer blocks or methods.
Try something like this:
public class Hellomsg {
{
System.out.println("Hello.");
}
}
or this
public class Hellomsg {
public void printMessage(){
System.out.println("Hello.");
}
}
You have a method call outside of a method which is not possible.
Correct code Looks like:
public class Hellomsg {
public static void main(String[] args) {
System.out.println("Hello.");
}
}
Just now I too faced the same issue, so I think I can answer this question.
You have to write the code inside the methods not on the class, class are generally used to do some initialization for the variables and writing methods.
So for your issue, I'm just adding your statement inside the main function.
package lab6;
public class Hellomsg {
public static void main(String args[]){
System.out.println("Hello.");
}
}
Execute the above, the code will work now.

Resources