Static mocked objects in JMockit - static

Consider a test as below -
public class TestSomething
{
#Mocked static SomeObject mocked;
#Test
public void testSomething()
{
new expectations() {{
mocked.doSomething();
}};
callSomething(mocked);
}
}
The issue is that mocked always turns out to be null because it is declared as static.
Can this be overridden?

No, #Mocked and the other mocking annotations only apply to instance fields of the test class (and to test method parameters as well).

Related

Powermock of static class gives error: java.lang.NoClassDefFoundError: Could not initialize class XXX

Problem
Could not initialize class ...
...javax.xml.transform.FactoryFinder (in our case).
In the article, where we found the solution, it was the class SessionFactory.
Class Under Test
We wanted to write a test for a utils class with static members.
We got the error when trying to create a Mock of a class, which contained a new statement as an initialization of a static field.
public class ClassUnderTest{
private static JavaType javaType = new JavaType();
// ...
}
Test Class
#RunWith(PowerMockRunner.class)
#PrepareForTest(ClassUnderTest.class)
public class TestForClassUnderTest {
#Test
public void testCase() {
PowerMockito.mockStatic(ClassUnderTest.class);
Solution
The solution was adding another class level annotation to the test class:
#SuppressStaticInitializationFor("com.example.package.util.ClassUnderTest")
Note, that you have to give the package path and no .class at the end. Unlike #PrepareFor.
Thanks to this article: http://www.gitshah.com/2010/06/how-to-suppress-static-initializers.html
Test Class with Solution
//...
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;
#RunWith(PowerMockRunner.class)
#PrepareForTest(ClassUnderTest.class)
#SuppressStaticInitializationFor("com.example.package.util.ClassUnderTest") // <-- this is it :)
public class TestForClassUnderTest {
#Test
public void testCase() {
PowerMockito.mockStatic(ClassUnderTest.class);
//...
}
}

Static class in Android

I have a question, I confuss about when I must use class static.
I understand that I have use class static when I need some methods that going to use many times in the code, and that class doesn´t need to be declarate, but in a example in android I find that code.
Where they declare a static class and call it with an instance...
Why did they do that?
public View getView(int position, View view, ViewGroup viewGroup) {
//View holder pattern
**ViewHolder holder;**
if(view ==null){
LayoutInflater layoutInflater=LayoutInflater.from(this.context);
view=layoutInflater.inflate(R.layout.list_item,null);
**holder=new ViewHolder();**
holder.txtView =(TextView) view.findViewById(R.id.txtView);
view.setTag(holder);
}
return view;
}
**static class ViewHolder{
private TextView txtView;
}**
Thanks for your explanation..
The advantage of having a static nested class over an non static one is, that to create an instance of the static nested class you don’t need an instance of the outer class. If you only have a non static inner class you need an object of the outer one to be able to create an instance.
Note that only nested classes can be static.

Kotlin object vs companion-object vs package scoped methods

I have written this methods in Kotlin and analysed the bytecode:
Situation 1
class A {
object b {
fun doSomething() {}
}
}
Situation 2
class A {
companion object b {
fun doSomething() {}
}
}
Situation 3
fun doSomething() {}
Bytecode Result
Situation 1: class Test$asb, public final doSomething()I
Situation 2: class Test$Companion, public final doSomething()I
Situation 3: class TestKt, public final static doSomething()I
My questions are:
I have an enum class, and I want to return an enum instace given an enum variable, for instance, findById (enum(id, color)). How would I do it? Companion Object? object?
It seems the only way to have a real static method is in package level, without class declaration. But that becomes a little bit too global. Is there any way to access it via: ClassName.staticMethod, staticMethod being really static.
Provide meaningfull examples of package declaration methods, companion object and object.
Context. I have been coding in Kotlin and I find it amazing. But sometimes I need to make a decision: for example, a heavy immutable property which in java I would declare as static final, but in Kotlin I find it hard to "find an equivalent".
If you have a function which performs some action closely related to a class but doesn't require a class instance, such as your findById example, you should put it in the companion object of the class.
If you want to expose a method as a static method to Java code, you can annotate it with the #JvmStatic annotation.
If a function does not require an instance of a class, then it is your design decision where to put it. Use package level if it is package-specific, use a class companion if it closely relets to the class (for example other classes in the package have similar functions).
Note that enum has several in-build properties and patterns:
enum class Colour(val value: Int) {
black(100), red(200), green(300)
}
fun colourById(id: Int) = Colour.values[id]
fun colourByValue(value: Int) = Colour.values.first {it.value == value}
fun colourByName(name: String) = Colour.valueOf(name)
I would suggest to develop voddan answer:
enum class Color {
RED,
BLUE,
GREEN;
companion object Utils {
fun findById(color: Color): Color {
return color;
}
}
}
And to test
#Test
fun testColor() {
println(Color.Utils.findById(Color.valueOf("RED")));
}

AngularJS: How to inject service to a static member of a regular class

I'm using typescript&angularJS for a project and I have a public class (not controller, just a regular class) to hold some enums, is that possible I can instantiate a static member of this class with a service object?
With Controller, it's very easy to use DI of AngularJS to instantiate a service object but for a regular class, I don't know how to do it.
Thanks.
Add code snippet:
export public Enums {
public static serviceObj; //how to instantiate serviceObj with some service?
}
Not exactly sure what you're asking but is this what you're looking for?
interface ServiceObj {
}
class Enums {
public static serviceObj : ServiceObj;
}
Enums.serviceObj = [set from some external location]

Importing a class with a specific parameter

I got a ViewModel which I export with MEF. I'd like this ViewModel to be initialized differently each time it's being imported, according to an enum/specific object parameter that will be provided to it.
I've been reading a little on the subject and I found that maybe this -
http://msdn.microsoft.com/en-us/library/ee155691.aspx#metadata_and_metadata_views
would be able to fit my needs, but I'm not sure that this would be the best way to do it.
Another method I've been thinking about is importing the class normally, and then once I've an instance, to call a special initialization method that would receive my parameter. However this doesn't seem like a classic MEF implementation, and maybe losses some of its "magic".
I'm hoping someone would be able to point out for me what would be the recommended method to achieve this.
Thanks!
A workaround is exporting a factory that creates instances of your type. While this means you cannot directly import thos instances, it does have the benefit that the logic to create them is the responsability of the factory so users of the class do not have to know about it:
public class ServiceWithParameter
{
public ServiceWithParameter( int a )
{
this.a = a;
}
private readonly int a;
}
[Export]
public class ServiceWithParameterFactory
{
public ServiceWithParameterFactory()
{
instance = 0;
}
public ServiceWithParameter Instance()
{
return new ServiceWithParameter( instance++ );
}
private int instance;
}
//now everywhere you need ServiceWithParameter:
[Import]
ServiceWithParameterFactory serviceFactory;
var instanceA = serviceFactory.Instance(); //instanceA.a = 0
var instanceB = serviceFactory.Instance(); //instanceB.a = 1
A more extensible way is telling the container you have a factory and an example is presented here: http://pwlodek.blogspot.com/2010/10/mef-object-factories-using-export.html

Resources