Castle Windsor not intercepting DataException - castle-windsor

I have a class to intercept DataException which implements the IInterceptor interface, however the Intercept method is not being called.
I'm registering the interceptor class this way:
container.Register(Component.For<DatabaseErrorInterceptor>().LifestyleTransient());
Here is the interceptor class:
public class DatabaseErrorInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
try
{
invocation.Proceed();
}
catch (DataException exc)
{
throw this.MapearExcecao(excecao);
}
}
private BusinessRuleException HandleException(DataException databaseError)
{
// ...
return new BusinessRuleException(...);
}
}

We found the answer to this problem, it was missing a call to container.Kernel.ProxyFactory.AddInterceptorSelector(...);

Related

ES6 Extending BaseClass without calling constructor and when I am trying to call a method in my subclass throwing error

Extending BaseClass without calling constructor and when I am trying to call a method in my subclass throwing error
class BaseClass {
constructor(cfg) {
// Transfer all properties to class object
Object.assign(this, cfg);
if(this.el instanceof HTMLElement === false) {
return;
}
this.setup();
}
setup() {
this.isSetup = true;
}
}
Do I need to call constructor to access this object in current class ?
class MyClass extends BaseClass {
setup() {
// Calling super
super.setup();
this.show(); **// this.show is not a function**
}
show = () => {
console.log('called');
}
}

Not able to partial mock static method with PowerMockito

I am to mock a static function named toBeMockedFunction in Util class. This method is called from toBeUnitTested which is a public static void method. I want toBeMockedFunction to do nothing. I tried many approaches (snippet posted of such 2) of partial mock and stubbing and unable to succeed.
Please suggest what I am doing wrong.
public class Util {
// Some code
public static void toBeUnitTested(CustomObject cb, CustomObject1 cb1, List<CustomObject2> rows, boolean delete) {
// some code
toBeMockedFunction(cb, "test", "test");
}
public static CustomObject toBeMockedFunction(CustomObject cb, String str1) {
// some code
}
}
And below is my junit class
#RunWith(PowerMockRunner.class)
#PrepareForTest({ Util.class})
public class UtilTest {
#Test
public void Test1() {
PowerMockito.spy(Util.class);
//mock toBeMocked function and make it do nothing
PowerMockito.when(PowerMockito.spy(Util.toBeMockedFunction((CustomObject)Mockito.anyObject(), Mockito.anyString()))).thenReturn(null);
Util.toBeUnitTested(cb, "test", "test");
}
}
Approach2
PowerMockito.mockStatic(Util.class);
PowerMockito.when(Util.toBeUnitTested((CustomObject)Mockito.anyObject(),Mockito.anyString())).thenCallRealMethod();
Util.toBeUnitTested(cb, "test", "test");
This is an example of how can do that:
#RunWith(PowerMockRunner.class)
#PrepareForTest({ Util.class})
public class UtilTest {
#Test
public void Test1() {
PowerMockito.spy(Util.class);
PowerMockito.doReturn(null).when(Util.class, "toBeMockedFunction", Mockito.any(CustomObject.class), Mockito.anyString(), Mockito.anyString());
List<CustomObject2> customObject2List = new ArrayList<>();
customObject2List.add(new CustomObject2());
Util.toBeUnitTested(new CustomObject(), new CustomObject1(), customObject2List, true);
}
}
Please note that the code of your OP doesn't compile. Method toBeMockedFunction(CustomObject cb, String str1) receives only 2 parameters and you are calling with 3: toBeMockedFunction(cb, "test", "test");. As you could see, I've added the last one to the method signature.
Hope it helps

Powermockito unable to mock the super call

So basically I'm trying to write a Junit using powermockito for a adapter for a service class which consumes a webservice.
I have an adapter with a constructor that inturn creates a new service object in it's own constructor by calling a super class. I have to test my adapter. I have used power mockito to mock my adapter as well as my service class but I don't think the mocked object is able to perform the super call. The following is the structure of my code. I want the super class to return my mocked object upon call.
public class CommonPoolingServiceAdp {
private CPSSecurity cpsServicePort;
public CommonPoolingServiceAdp() {
CommonPoolingService service= new CommonPoolingService();
cpsServicePort=service.getCommonPoolingServicePort();
}
public SercurityDataResponse getBroadcastElements(broadcastReqObj)
{
SercurityDataResponse=null;
response=cpsServicePort.getBroadcastElements(broadcaseRequestObj);
}
}
public class CommonPoolingService extends Service {
{
static
{
//few mandatory initializations
}
public CommonPoolingService()
{
super(WSDL_Location,QName);
}
public CSPSecurity getCommonPoolingServicePort() {
return super.getPort(QName);
}
}
}
Please share a bit more of your code. By the way, this is how you mock a super class method :
public class SuperClass {
public void method() {
methodA(); // I don't want to run this!
}
}
public class MyClass extends SuperClass{
public void method(){
super.method()
methodB(); // I only want to test this!
}
}
#Test
public void testMethod() {
MyClass spy = Mockito.spy(new MyClass());
// Prevent/stub logic in super.method()
Mockito.doNothing().when((SuperClass)spy).methodA();
// When
spy.method();
// Then
verify(spy).methodB();
}
Hope, it will help.

Have Castle Windsor select component based on requestor type namespace

I have an interface ISession whose instance is produced by a different Session Factory depending on which namespace the class belongs to.
Example of my component registration:
IWindsorContainer container = new WindsorContainer();
container.Register(Component.For<NHibernate.ISession>()
.UsingFactoryMethod((kernel, creationContext) =>
{
NHibernate.ISession session =
new SessionFactoryForNamespace1()
.Instance.GetSession();
return session;
})
.LifestylePerWebRequest());
container.Register(Component.For<NHibernate.ISession>()
.UsingFactoryMethod((kernel, creationContext) =>
{
NHibernate.ISession session =
new SessionFactoryForNamespace2()
.Instance.GetSession();
return session;
})
.LifestylePerWebRequest());
container.Register(Component.For<Namespace1.IRepository1()
.ImplementedBy<Namespace1.Repository1>());
container.Register(Component.For<Namespace2.IRepository2>()
.ImplementedBy<Namespace2.Repository2>());
Example of the resolution graph:
public class MyController
{
public MyController(Namespace1.IRepository1 repo1,
Namespace2.IRepository2 repo2) { }
}
namespace Namespace1
{
public interface IRepository1 { }
public class Repository1 : IRepository1
{
public Repository1(NHibernate.ISession session) { }
}
}
namespace Namespace2
{
public interface IRepository2 { }
public class Repository2 : IRepository2
{
public Repository2(NHibernate.ISession session) { }
}
}
When Castle Windsor is asked to resolve MyController, it then tries to resolve IRepository1 and IRepository2, and subsequently the ISession for each. I want to have Castle Windsor select the component handlers based on the requestor type's namespace which in my example is either Namespace1 or Namespace2.
I am new to Castle Windsor and not sure where in the resolution pipeline I'm supposed to be plugging into.
What is the best approach to accomplish what I have outlined above?
I think a service override would work for this.
UPDATE:
I also did an article on some of Windsor's advanced features (including a section on Service Overrides) that should augment the documentation linked above.
Here is how I implemented service override solution:
Repository interfaces now inherit from a common repository interface:
public class MyController
{
public MyController(Namespace1.IRepository1 repo1,
Namespace2.IRepository2 repo2) { }
}
public interface IRepository { }
namespace Namespace1
{
public interface IRepository1 : IRepository { }
public class Repository1 : IRepository1
{
public Repository1(NHibernate.ISession session) { }
}
}
namespace Namespace2
{
public interface IRepository2 : IRepository { }
public class Repository2 : IRepository2
{
public Repository2(NHibernate.ISession session) { }
}
}
Repository component registeration based on its namespace:
IWindsorContainer container = new WindsorContainer();
...
Action<Type> RegisterRepository = t =>
{
container.Register(
AllTypes.FromAssemblyContaining(t)
.BasedOn(typeof(IRepository))
.WithServiceAllInterfaces()
.Configure(c =>
{
c.DependsOn(
ServiceOverride
.ForKey<NHibernate.ISession>()
.Eq(c.Implementation.Namespace));
c.LifeStyle.Is(LifestyleType.Transient);
})
);
};
RegisterRepository(typeof(Namespace1.IRepository1));
RegisterRepository(typeof(Namespace2.IRepository2));
Seems to work :)

Castle and generics

Considering this code :
interface IRepository<T>
{
void Save();
}
class Repository<T>
{
public virtual void Save() // something
{ }
}
interface IOtherRepository : IRepository<OtherClass>
{
void Other();
}
class OtherRepository : Repository<OtherClass>, IOtherRepository
{
public override void Save() // something different
{ }
public override void Other(){ }
}
How is it possible to configure Castle Windsor to give me an instance of OtherRepository when I call container.Resolve<IRepository<OtherClass>> ?
If Castle Windsor can't do this, which ioc containers can ?
var container = new WindsorContainer();
container.Register(Component.For(typeof(IRepository<>))
.ImplementedBy(typeof(Repository<>));
container.Register(Component.For<IRepository<OtherClass>, IOtherRepository>()
.ImplementedBy<OtherRepository>());
var repo = container.Resolve<IRepository<Something>>();
Assert.IsInstanceOfType(typeof(Repository<Something>), repo);
var specificRepo = container.Resolve<IRepository<OtherClass>>();
Assert.IsInstanceOfType(typeof(OtherRepository), specificRepo);
var otherRepo = container.Resolve<IOtherRepository>();
Assert.AreSame(otherRepo, specificRepo);