Using JMockIt, Unable to Deencapsulate the private constructor of an enum singleton - jacoco

I have an enum singleton with private constructor; while I could get all my methods unit tested and covered by Jacoco but Jacoco coverage seemed low mainly because of the private constructor I believe; To get the better numbers, I have decided to give a go to Deencapsulate the private constructor and create the instance but JMocKIt complains that it cannot find the compatible constructor.
public enum Adapter implements HimTranscriptionFrameworkAdapter {
/** Singleton Instance. */
INSTANCE;
/**
* Initializes the Adapter.
*/
private Adapter() {
isStarted = false;
}
public void startup() throws Exception {}
}
and I have this in my test:
Adapter deencapsulatedAdapter =
Deencapsulation.newInstance(Adapter.class);
deencapsulatedAdapter.startup();
and I get this error:
java.lang.IllegalArgumentException: No compatible constructor found:
Adapter()
I would to seek your help in this regard.

Related

PowerMock.expectPrivate behavior

I am writing test cases using EasyMock and PowerMock, and I want to modify the behavior of a private method so I am using below
PowerMock.expectPrivate(myClass, "m2", "Hello").andReturn("Something");
Now when this expect private statement is executed, it is actually invoking the REAL method.
This real method invocation is causing an issue because the private method has a few variables which are not available during the test execution and that's the reason why I want to mock this private method!
Above is defeating the purpose of private method mocking!!! Is that correct?
Below is my example class
#RunWith(PowerMockRunner.class)
#PrepareForTest({ReplicatePrivateMock.class})
public class ReplicatePrivateMock {
#Test
public void testPrivate() throws Exception {
MyClass myClass = new MyClass();
PowerMock.expectPrivate(myClass, "m2", "Hello").andReturn("Something");
System.out.println(myClass.m1("Hello"));
}
private class MyClass {
private StringBuilder builder;
public String m1(String s) {
return m2(s);
}
private String m2(String s) {
return builder.append(s) + s;
}
}
}
In this, I am mocking the call to m2() method but that throws NPE because m2 is using builder variable which is null!
Please let me know how to ACTUALLY mock the private method. Thanks very much.

Unit test for EJB with #PostConstruct method

Consider the following sample code:
#Stateless
public class MyBean {
private SomeHelper helper;
private long someField;
#PostConstruct
void init() {
helper = new SomeHelper();
someField = initSomeField();
}
long initSomeField() {
// perform initialization
}
public void methodToTest() {
helper.someMethod();
long tmp = 3 + someField;
}
}
And here is the test template, that I always use
public class MyBeanTest {
#Spy
#InjectMocks
private MyBean testSubject;
#Mock
private SomeHelper mockedHelper;
#Before
public void before() {
MockitoAnnotations.initMocks(this);
doReturn(1L).when(testSubject).initSomeField();
}
#Test
public void test() {
testSubject.methodToTest();
// assertions
}
}
The problem with testing methodToTest is that it needs field someField to be initialized. But the initialization is done in #PostConstruct method. And I can't run this method before call to testSubject.methodToTest(), because it will re-initialize helper. Also, I don't want to manually set up all the mocks. And I don't want to use reflection to set the someField, because that would make MyBeanTest vulnerable to MyBean refactoring. Can anybody propose, maybe better design to avoid situations like this?
A few notes:
Logic in initSomeField could be quite heavy (including calls to database), so I want to initialize it only once in a #PostConstruct method.
I don't want to create a setter for this field or widen its access modifier, because that would allow unwanted changes to my field.
If your test is in the same package as your class, then you can just call initSomeField directly, since it's package private. You can either do this in each individual test method, or in your #Before method, provided it runs after initMocks.

How to divert "non public" method in public class moles

I have a public method that uses a local private method to get data from the Db.
private string SomeMethod(string)
{
...
Doing some operations
...
string data = GetDBData(string);
Doing some operations
...
}
I want to divert/isolate the private method GetDBData(string) using moles so my test will not require the DB.
Obviously, my question is: how to do it?
thank you
Uria
EDIT
Additional information:
i tried to change the method accessors both to public and internal protected,
in both cases i can now see the methods as moles.
BUT when running the test, the original method is still being used and not the detour I've implemented in the PexMethod.
You can try any of the following.
Make the method internal and add an attribute like this to the assembly:
[assembly: InternalsVisibleTo("<corresponding-moles-assembly-name>")]
Change the method access to protected virtual and then use a stub.
Refactor your class so that it gets an interface (IDataAccessObject) as a constructor parameter, SomeMethod being one of the methods of that interface, and then pass a stub of that interface to your class in test methods.
I figured it out
If i have the public MyClass with private SomeMethod
public class MyClass
{
private string SomeMethod(string str){}
}
if you want to mole the SomeMethod method you need to use AllInstances in the test method:
[PexMethod]
SomeMethod(string str)
{
MMyClass.AllInstances.SomeMethod = (instance, str) => { return "A return string"; };
}
notice that the lambda receives an instance parameter as the first parameter. I'm not sure what it's function is.

A .NET Unit Test without a parameterless constructor, to facilitate dependency injection

I'm trying to have the unit tests not rely on calling container.Resolve<T>() for their dependencies.
I'm currently using AutoFac 2.2.4, and tried xUnit.NET and NUnit, but both have this issue:
No parameterless constructor defined for this object
How do I get past this issue? Is it a particular unit testing framework that will support this, or just how said framework is configured?
Should I not be doing this? Or can I set up the test class to work with the constructor that has it's only dependency?
Here's some of the code:
public class ProductTests : BaseTest
{
readonly private IProductRepository _repo;
public ProductTests(IProductRepository r)
{
_repo = r;
}
//working unit tests here with default constructor
}
Did I choose to initialise the container wrongly in the base class constructor?
public abstract class BaseTest
{
protected BaseTest()
{
var builder = new ContainerBuilder();
builder.RegisterType<ProductRepository>().As<IProductRepository>();
builder.Build();
}
}
The initial problem is indeed due to how the testing frameworks are designed. They all require a parameterless constructor in order to instantiate test instances. And rightfully so. With these frameworks, the constructor is not to be relied on for test initialization. That is the purpose of the SetUp method. All in all, the test classes themselves are not suited for injection.
And IMO, this becomes a non-issue when you develop your tests to not depend on the container. After all, each test class should focus on one "system under test" (SUT). Why not have the setup method instantiate that system directly and provide each dependency (usually in the form of fakes)? By doing it this way you have effectively removed another unnecessary dependency from your tests, namely the IoC framework.
On a side note: the only time I involve the IoC framework in my tests is in my "container tests". These tests focus on verifying that certain services can be resolved from the container after the container have been initialized with application or assembly modules.
I just allow my tests to have a dependency on Autofac, although I encapsulate it. All of my TestFixtures inherit from Fixture, which is defined as such:
public class Fixture
{
private static readonly IContainer MainContainer = Ioc.Build();
private readonly TestLifetime _testLifetime = new TestLifetime(MainContainer);
[SetUp]
public void SetUp()
{
_testLifetime.SetUp();
}
[TearDown]
public void TearDown()
{
_testLifetime.TearDown();
}
protected TService Resolve<TService>()
{
return _testLifetime.Resolve<TService>();
}
protected void Override(Action<ContainerBuilder> configurationAction)
{
_testLifetime.Override(configurationAction);
}
}
public class TestLifetime
{
private readonly IContainer _mainContainer;
private bool _canOverride;
private ILifetimeScope _testScope;
public TestLifetime(IContainer mainContainer)
{
_mainContainer = mainContainer;
}
public void SetUp()
{
_testScope = _mainContainer.BeginLifetimeScope();
_canOverride = true;
}
public void TearDown()
{
_testScope.Dispose();
_testScope = null;
}
public TService Resolve<TService>()
{
_canOverride = false;
return _testScope.Resolve<TService>();
}
public void Override(Action<ContainerBuilder> configurationAction)
{
_testScope.Dispose();
if (!_canOverride)
throw new InvalidOperationException("Override can only be called once per test and must be before any calls to Resolve.");
_canOverride = false;
_testScope = _mainContainer.BeginLifetimeScope(configurationAction);
}
}

Unit testing with singletons

I have prepared some automatic tests with the Visual Studio Team Edition testing framework. I want one of the tests to connect to the database following the normal way it is done in the program:
string r_providerName = ConfigurationManager.ConnectionStrings["main_db"].ProviderName;
But I am receiving an exception in this line. I suppose this is happening because the ConfigurationManager is a singleton. How can you work around the singleton problem with unit tests?
Thanks for the replies. All of them have been very instructive.
Have a look at the Google Testing blog:
Using dependency injection to avoid singletons
Singletons are Pathological Liars
Root Cause of Singletons
Where have all the Singletons Gone?
Clean Code Talks - Global State and Singletons
Dependency Injection.
And also:
Once Is Not Enough
Performant Singletons
Finally, Misko Hevery wrote a guide on his blog: Writing Testable Code.
You can use constructor dependency injection. Example:
public class SingletonDependedClass
{
private string _ProviderName;
public SingletonDependedClass()
: this(ConfigurationManager.ConnectionStrings["main_db"].ProviderName)
{
}
public SingletonDependedClass(string providerName)
{
_ProviderName = providerName;
}
}
That allows you to pass connection string directly to object during testing.
Also if you use Visual Studio Team Edition testing framework you can make constructor with parameter private and test the class through the accessor.
Actually I solve that kind of problems with mocking. Example:
You have a class which depends on singleton:
public class Singleton
{
public virtual string SomeProperty { get; set; }
private static Singleton _Instance;
public static Singleton Insatnce
{
get
{
if (_Instance == null)
{
_Instance = new Singleton();
}
return _Instance;
}
}
protected Singleton()
{
}
}
public class SingletonDependedClass
{
public void SomeMethod()
{
...
string str = Singleton.Insatnce.SomeProperty;
...
}
}
First of all SingletonDependedClass needs to be refactored to take Singleton instance as constructor parameter:
public class SingletonDependedClass
{
private Singleton _SingletonInstance;
public SingletonDependedClass()
: this(Singleton.Insatnce)
{
}
private SingletonDependedClass(Singleton singletonInstance)
{
_SingletonInstance = singletonInstance;
}
public void SomeMethod()
{
string str = _SingletonInstance.SomeProperty;
}
}
Test of SingletonDependedClass (Moq mocking library is used):
[TestMethod()]
public void SomeMethodTest()
{
var singletonMock = new Mock<Singleton>();
singletonMock.Setup(s => s.SomeProperty).Returns("some test data");
var target = new SingletonDependedClass_Accessor(singletonMock.Object);
...
}
Example from Book: Working Effectively with Legacy Code
Also given same answer here:
https://stackoverflow.com/a/28613595/929902
To run code containing singletons in a test harness, we have to relax the singleton property. Here’s how we do it. The first step is to add a new static method to the singleton class. The method allows us to replace the static instance in the singleton. We’ll call it
setTestingInstance.
public class PermitRepository
{
private static PermitRepository instance = null;
private PermitRepository() {}
public static void setTestingInstance(PermitRepository newInstance)
{
instance = newInstance;
}
public static PermitRepository getInstance()
{
if (instance == null) {
instance = new PermitRepository();
}
return instance;
}
public Permit findAssociatedPermit(PermitNotice notice) {
...
}
...
}
Now that we have that setter, we can create a testing instance of a
PermitRepository and set it. We’d like to write code like this in our test setup:
public void setUp() {
PermitRepository repository = PermitRepository.getInstance();
...
// add permits to the repository here
...
PermitRepository.setTestingInstance(repository);
}
You are facing a more general problem here. If misused, Singletons hinder testabiliy.
I have done a detailed analysis of this problem in the context of a decoupled design. I'll try to summarize my points:
If your Singleton carries a significant global state, don’t use Singleton. This includes persistent storage such as Databases, Files etc.
In cases, where dependency on a Singleton Object is not obvious by the classes name, the dependency should be injected. The need to inject Singleton Instances into classes proves a wrong usage of the pattern (see point 1).
A Singleton’s life-cycle is assumed to be the same as the application’s. Most Singleton implementations are using a lazy-load mechanism to instantiate themselves. This is trivial and their life-cycle is unlikely to change, or else you shouldn’t use Singleton.