Trouble mocking a private method - typemock

So, I am having an issue mocking a private method. From everything I have seen it should work, but isn't.
Let's start with the basics - Here is the code under test
public sealed class UnderTest
{
private bool MockPrivate(string name)
{
[snip]
}
private string MethodUnderTest(ParameterHolder parameters)
{
if (!this.MockPrivate(parameters.Parameter2))
{
return null;
}
[Snip]
}
[Snip]
}
public sealed class ParameterHolder
{
public ParameterHolder (bool parameter1, string parameter2)
{
this.Parameter1 = parameter1;
this.Parameter2 = parameter2;
}
public bool Parameter1
{
get;
private set;
}
public string Parameter2
{
get;
private set;
}
}
Here is the test method
public void Test_UnderTest_MethodUnderTest()
{
UnderTest testClass;
ParameterHolder parameters;
dynamic h;
testClass = new UnderTest();
parameters = Isolate.Fake.Instance<ParameterHolder>(Members.CallOriginal);
Isolate.WhenCalled(() => parameters.Parameter1).WillReturn(true);
Isolate.WhenCalled(() => parameters.Parameter2).WillReturn("parameter2value");
h = testClass.AsDynamic();
Isolate.WhenCalled(() => h.MockPrivate((string)null)).WillReturn(true);
Assert.IsNotNull(h.MethodUnderTest(parameters));
}
I have also tried to change the isolate call to:
Isolate.WhenCalled(() => h.MockPrivate("parameter2value").WillReturn(true);
and
Isolate.WhenCalled(() => h.MockPrivate(parameters.Parameter2).WillReturn(true);
In all the cases, the MockPrivate method gets executed, instead of returning the mocked True value.
Any help would be appreciated.

Ok, did some more checking and this is the correct way:
Isolate.NonPublic.WhenCalled(testClass, "MockPrivate").WillReturn(true);

Related

Pointcut for classes inside different package or sub-packages marked Deprecated and at the time whenever they used or instantiated?

I want to write a point cut for class instantiation in various packages,like classes inside the subpackages inside com.kepler.xenon (eg.com.kepler.xenon.modules.ticklers.pojo.Tickler,
com.kepler.xenon.modules.product.pojo.Product etc).
//This is my advice
#Aspect
#Component
public class OxAspect {
#After("execution(* com.oxane.xenon..*new(..)) && #within(java.lang.Deprecated)")
public void myAdvice(final JoinPoint jp){
System.out.println(jp.getSignature().getName()+""+jp.getTarget().getClass());
}
}
//This is my class
package com.kepler.xenon.modules.ticklers.pojo;
#Deprecated
public Class Ticklers{
#Id
#TableGenerator(name = "TICKLERS_ID", table = "ID_GENERATOR", pkColumnName = "GEN_KEY", valueColumnName = "GEN_VALUE", pkColumnValue = "TICKLERS_ID", allocationSize = 1, initialValue = 1)
#GeneratedValue(strategy = GenerationType.TABLE, generator = "TICKLERS_ID")
#Column(name = "TICKLERS_ID", unique = true, nullable = false)
private int ticklersId;
#Column(name = "TASK", nullable = false, length = 256)
private String taskName;
public int getTicklersId() {
return ticklersId;
}
public void setTicklersId(int ticklersId) {
this.ticklersId = ticklersId;
}
public String getTaskName() {
return taskName;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
}
What i want is that if anyone tries to access the class which is deprecated,then pointcut filters that call and triggers advice.
I have done it for methods but i am failing to do it for classes.
I am adding aspect which works for methods,controller and Dao
#Aspect
#Component
public class OxAspect {
private final OxAspectService oxAspectService;
public OxAspect(OxAspectService oxAspectService) {
this.oxAspectService=oxAspectService;
}
#Pointcut("execution(#java.lang.Deprecated * com.oxane.xenon..*(..))"
+ " || execution(* com.oxane.xenon..*.*(..)) && #within(java.lang.Deprecated)")
public void deprecated() {
}
#Before("deprecated()")
public void log(final JoinPoint jp) {
oxAspectService.logDeprecatedMethod(jp);
}
}
Edit:
I have done some research on spring io and found that it can't be done using spring aop. I have to use load time weaving or compile time weaving to achieve what i want. For that i have to use pure aspect j implementation. Correct me if i am wrong.
If I were you I will devide #Pointcut to signle condition like below:
#Pointcut("execution(* com.oxane.xenon..*(..))")
public void anyClassInSubpackage() {
}
#Pointcut("#annotation(java.lang.Deprecated)")
public void deprecatedClass() {
}
#Pointcut("execution(* com.oxane.xenon..*new(..))")
public void anyMethodInSubpackege() {
}
#Pointcut("#within(java.lang.Deprecated)")
public void deprecatedMethod() {
}
#Before("(anyClassInSubpackage() && deprecatedClass()) || (anyMethodInSubpackege() && deprecatedMethod())")
public void myAdvice(final JoinPoint jp){
//TODO
}

NInject kernel GetAll returns empty

I've two projects (class library projects) which implement one interface:
The first one:
public class MailPlugin : Extensibility.IProductorPlugin
{
...
}
The second one:
public class FileSystemPlugin : Extensibility.IProductorPlugin
{
...
}
Extensibility.IProductorPlugin, is a interface of a third project:
namespace Extensibility
{
public delegate void NotifyDigitalInputs(List<Domain.DigitalInput> digital_inputs);
public interface IProductorPlugin
{
String Name { get; }
String Description { get; }
String Version { get; }
List<Domain.Channel> AvailableChannels { get; }
IEnumerable<Guid> TypeGuids { get; }
event NotifyDigitalInputs OnDigitalInputs;
}
}
In my composition root, I've created this class:
namespace UI
{
public sealed class NinjectServiceLocator
{
private static readonly Lazy<NinjectServiceLocator> lazy = new Lazy<NinjectServiceLocator>(() => new NinjectServiceLocator());
public static NinjectServiceLocator Instance { get { return lazy.Value; } }
public Ninject.IKernel Kernel { get; private set; }
private NinjectServiceLocator()
{
using (var k = this.Kernel = new Ninject.StandardKernel())
{
k.Bind(b => b.FromAssembliesMatching("*")
.SelectAllClasses()
.InheritedFrom(typeof(Extensibility.IProductorPlugin))
.BindAllInterfaces()
);
}
}
}
}
So, when I want to look for all plugins, I just perform this:
protected void initialize()
{
foreach (Extensibility.IProductorPlugin productor_plugin in NinjectServiceLocator.Instance.Kernel.GetAll(typeof(Extensibility.IProductorPlugin)))
{
using (var channel_tile = new DevExpress.XtraBars.Docking2010.Views.WindowsUI.Tile() { Group = "Plugin Channels" })
{
foreach (Domain.Channel channel in productor_plugin.AvailableChannels)
{
channel_tile.Elements.Add(new DevExpress.XtraEditors.TileItemElement() { Text = channel.Name });
channel_tile.Elements.Add(new DevExpress.XtraEditors.TileItemElement() { Text = channel.Description });
this.tileContainer1.Items.Add(channel_tile);
}
}
}
}
However, GetAll returns anything.
What am I doing wrong?
I'll appreciate a lot your help.
Thanks for all.
try removing the using() from around the Kernel instantiation. a using will dispose the object at the end of the scope, which we don't want for a kernel.
using (var k = this.Kernel = new Ninject.StandardKernel())

NSubstitute: Arg.Do does not fulfill the list of called parameters

For the code bellow I get this assert failure and do not know why:
Assert.AreEqual failed. Expected:<2>. Actual:<0>.
public interface IA
{
void MethodA(B b);
}
public class A : IA
{
public void MethodA(B b) {/*no matter*/}
}
public class B
{
public string PropertyB { get; set; }
}
public class MyLogic
{
private IA _a;
public MyLogic(IA a)
{
_a = a;
}
public void DoLogic()
{
_a.MethodA(new B { PropertyB = "first" });
_a.MethodA(new B { PropertyB = "second" });
}
}
[TestClass]
public class MyLogicTests
{
[TestMethod]
public void CallTwiceAndCheckTheParams()
{
List<B> args = new List<B>();
IA a = Substitute.For<IA>();
new MyLogic(a).DoLogic();
a.Received(2).MethodA(Arg.Do<B>(x => args.Add(x)));
Assert.AreEqual(2, args.Count);
}
}
The code is setting up an action to perform (Arg.Do) after the calls have already been made. I think this is what you are after:
List<B> args = new List<B>();
IA a = Substitute.For<IA>();
a.MethodA(Arg.Do<B>(x => args.Add(x))); // do this whenever MethodA is called
new MyLogic(a).DoLogic();
a.Received(2).MethodA(Arg.Any<B>());
Assert.AreEqual(2, args.Count);

Passing complex navigation parameters with MvvmCross ShowViewModel

My complex type wouldn't pass from Show to Init method even with configured MvxJsonNavigationSerializer as specified here Custom types in Navigation parameters in v3
public class A
{
public string String1 {get;set;}
public string String2 {get;set;}
public B ComplexObject1 {get;set;}
}
public class B
{
public double Double1 {get;set;}
public double Double2 {get;set;}
}
When I pass instance of object A to ShowViewModel method I receive this object with String1 & String2 deserialized correctly but CopmlexObject1 is null.
How to deal with complex object MvvmCross serialization?
I believe there may be some gremlins in that previous answer - will log as an issue :/
There are other possible routes to achieve this type of complex serializable object navigation still using Json and overriding parts of the framework, but actually I think that it might be better to just use your own BaseViewModel's to do serialization and deserialization - e.g. use serialization code like:
public class BaseViewModel
: MvxViewModel
{
private const string ParameterName = "parameter";
protected void ShowViewModel<TViewModel>(object parameter)
where TViewModel : IMvxViewModel
{
var text = Mvx.Resolve<IMvxJsonConverter>().SerializeObject(parameter);
base.ShowViewModel<TViewModel>(new Dictionary<string, string>()
{
{ParameterName, text}
});
}
}
with deserialization like:
public abstract class BaseViewModel<TInit>
: MvxViewModel
{
public void Init(string parameter)
{
var deserialized = Mvx.Resolve<IMvxJsonConverter>().DeserializeObject<TInit>(parameter);
RealInit(deserialized);
}
protected abstract void RealInit(TInit parameter);
}
then a viewModel like this:
public class FirstViewModel
: BaseViewModel
{
public IMvxCommand Go
{
get
{
return new MvxCommand(() =>
{
var parameter = new A()
{
String1 = "Hello",
String2 = "World",
ComplexObject = new B()
{
Double1 = 42.0,
Double2 = -1
}
};
ShowViewModel<SecondViewModel>(parameter);
});
}
}
}
can navigate to something like:
public class SecondViewModel
: BaseViewModel<A>
{
public A A { get; set; }
protected override void RealInit(A parameter)
{
A = parameter;
}
}
A small addition to Stuart's answer to add type safety:
public class BaseViewModel: MvxViewModel {
protected bool ShowViewModel<TViewModel, TInit>(TInit parameter) where TViewModel: BaseViewModel<TInit> {
var text = Mvx.Resolve<IMvxJsonConverter>().SerializeObject(parameter);
return base.ShowViewModel<TViewModel>(new Dictionary<string, string> { {"parameter", text} });
}
}
public abstract class BaseViewModel<TInit> : BaseViewModel {
public void Init(string parameter)
{
var deserialized = Mvx.Resolve<IMvxJsonConverter>().DeserializeObject<TInit>(parameter);
RealInit(deserialized);
}
protected abstract void RealInit(TInit parameter);
}
ShowViewModel method now takes the same parameter type that the RealInit method instead of an object type. Also, BaseViewModel<TInit> inherits from BaseViewModel so their instances can also call the new ShowViewModel method.
The only drawback is that you have to explicitly specify the parameter type in the call like this:
ShowViewModel<StoreInfoViewModel, Store>(store);

NHibernate: single lazy load property

Update: I'm now convinced that the problem lies in the fact that Document is configured as non lazy. The problem is that I don't control the base class and that means I can't change the base props to virtual...
After reading the docs, I'm under the assumption that I should be able to have a non lazy class with a lazy property. Is this possible? Here's the code I'm using for mapping my class:
public class DocumentoMapping : ClassMap<Documento> {
public DocumentoMapping()
{
Setup();
}
private void Setup()
{
Table("Documentos");
Not.LazyLoad();
Id(doc => doc.Id, "IdDocumentos")
.GeneratedBy.Identity()
.Default(0);
Map(doc => doc.NomeDocumento)
.Not.Nullable();
Map(doc => doc.Descricao);
Map(doc => doc.Bytes, "Documento")
.CustomSqlType("image")
.CustomType<Byte[]>()
.LazyLoad()
.Length(2000000000);
Component(doc => doc.Acao,
accao =>
{
accao.Map(a => a.Login);
accao.Map(a => a.Data);
accao.Map(a => a.UserAD)
.CustomSqlType("int")
.CustomType<ADs>();
})
.Not.LazyLoad();
Map(doc => doc.IdPedidoAssistencia)
.Column("IdPats")
.Not.LazyLoad();
}
}
And here's the code for my class:
public class Documento : Entity, IHasAssignedId<int>{
public virtual Byte[] Bytes { get; private set; }
public Documento()
{
NomeDocumento = Descricao = "";
Acao = new Acao("none", DateTime.Now, ADs.Sranet);
}
public Documento(string nomeDocumento, string descricao, Acao acao)
{
Contract.Requires(!String.IsNullOrEmpty(nomeDocumento));
Contract.Requires(!String.IsNullOrEmpty(descricao));
Contract.Requires(acao != null);
Contract.Ensures(!String.IsNullOrEmpty(NomeDocumento));
Contract.Ensures(!String.IsNullOrEmpty(Descricao));
Contract.Ensures(Acao != null);
NomeDocumento = nomeDocumento;
Descricao = descricao;
Acao = acao;
}
[DomainSignature]
public String NomeDocumento { get; private set; }
[DomainSignature]
public String Descricao { get; private set; }
[DomainSignature]
public Acao Acao { get; private set; }
internal Int32 IdPedidoAssistencia { get; set; }
internal static Documento CriaNovo(String nomeDocumento, String descricao, Byte[] bytes, Acao acao)
{
Contract.Requires(!String.IsNullOrEmpty(nomeDocumento));
Contract.Requires(!String.IsNullOrEmpty(descricao));
Contract.Requires(bytes != null);
Contract.Requires(acao != null);
var documento = new Documento(nomeDocumento, descricao, acao) { Bytes = bytes };
return documento;
}
public void ModificaBytes(Byte[] bytes)
{
Contract.Requires(bytes != null);
Bytes = bytes;
}
public void SetAssignedIdTo(int assignedId)
{
Id = assignedId;
}
[ContractInvariantMethod]
private void Invariants()
{
Contract.Invariant(NomeDocumento != null);
Contract.Invariant(Descricao != null);
Contract.Invariant(Acao != null);
}
}
Base classes are the just for the basic stuff, ie, setting Id and injecting base code for instance comparison. At first sight, I can't really see anything wrong with this code. I mean, the property is virtual, the mapping says it should be virtual, so why does loading it with Get forces a complete load of the properties? For instance, this code:
var d = sess.Get(148);
Ends up generating sql for loading all the properties on the table. Did I get this wrong?
thanks!
Yes, it's confirmed: in order to have lazy load properties on a class, the class will also need to be lazy.