asmock Previous method requires a return value or an exception to throw - apache-flex

Trying to get my head around asmock to implement some unit testing in my project. I want to test my MainMediator and since there are objects that get created in my MainMediator onRegister call, I'm thinking that I should mock those objects.
Hopefully that's correct to begin with!
I have something like this
[Rule] public var includeMocks : IncludeMocksRule = new IncludeMocksRule([
IEventDispatcher, IMyService
]);
[Before]
public function setUp():void {
mockRepository = new MockRepository();
mainView = new MainView();
mainMediator = new MainMediator();
dispatcher = IEventDispatcher(mockRepository.createStub(IEventDispatcher, StubOptions.NONE));
myService = IMyService(mockRepository.createStub(IMyService, StubOptions.NONE));
mockRepository.stubEvents(dispatcher);
SetupResult.forCall(chatService.clientID)
.returnValue("");
mockRepository.replayAll();
mainMediator.eventDispatcher = dispatcher;
myService.eventDispatcher = dispatcher;
mainMediator.service = myService;
....
mainMediator.onRegister();
}
When I step through the test and stop at mockRepository.stubEvents(dispatcher). I can see errors in the myService class
Error: Previous method IMyService/clientID/get(); requires a return value or an exception to throw. clientID just happens to be my first property hence why it's being picked on.
I thought either that StubOptions.NONE would mean that no properties get stubbed or that my SetupResult.forCall(myService.clientID) would fix it but none did.
Answering to the question in the comment re: the eventDispatcher, I have:
MyService extends ServiceBase implements IMyService
where ServiceBase extends Actor
I found that I need the following in IMyService to get access to the eventDispatcher.
function get eventDispatcher():IEventDispatcher;
function set eventDispatcher(dispatcher:IEventDispatcher):void;
Not too sure if that is correct. Bit confused now.
Can someone please tell me where I'm going wrong?
Thanks!

This is a common problem when mocking concrete classes, rather than interfaces: if the constructor calls another method (or property getter), it will return null because it hasn't been mocked yet.
There's not really anyway to workaround it, except to abstract your class through an interface and mock that.

Related

KafkaListener annotation at class level with errorhandler property ignored

When using the kafkalistener annotation at class level and the provided errorhandler property is ignored. When method is annotated with kafkalistner and the provided errorhandler is working. Is it expected behavior?
This is really bug. The piece of code:
String errorHandlerBeanName = resolveExpressionAsString(kafkaListener.errorHandler(), "errorHandler");
if (StringUtils.hasText(errorHandlerBeanName)) {
endpoint.setErrorHandler(this.beanFactory.getBean(errorHandlerBeanName, KafkaListenerErrorHandler.class));
}
Is missed in the:
private void processMultiMethodListeners(Collection<KafkaListener> classLevelListeners, List<Method> multiMethods,
Object bean, String beanName) {
Unfortunately I don't see a simple way to workaround this. Please, consider to have a single #KafkaListener method with an Object as payload and manual type routing in that method to others.
Feel free to raise a GitHub issue on the matter!

Can I mock the values of a List<Microsoft.Bing.Speech.RecognitionPhrase> just like in the VS debugger?

When writing Unit Tests for a function that is consuming a List<Microsoft.Bing.Speech.RecognitionPhrase> I face the following error:
Invalid setup on a non-virtual (overridable in VB) member: x =>
x.Confidence
After reading here, I get that this is because the property is not virtual. I have been reading in the site about interfaces, wrappers, virtuals...but with no success.
I have access to RecognitionPhrase [from metadata] and it has public Confidence Confidence { get; } so there's no set here. I have tried to create a public interface IRecognitionPhrase and a public class RecognitionPhrase : IRecognitionPhrase, but then in the final casting it says that it cannot cast my RecognitionPhrase to Microsoft.Bing.Speech.RecognitionPhrase.
I have read something about reflection but it seems to work with private setters rather than with no setters.
I'm out of ideas now. Any directions are much appreciated (and of course if someone has already mocked List<Microsoft.Bing.Speech.RecognitionPhrase> please comment how did you do it) Thanks
I'm open to employing any other testing framework.
I've finally solved it using reflection...but not reflection of the Mock (which was throwing an exception)
//var mockFrase = new Mock<RecognitionPhrase>();
//PropertyInfo propertyInfo = mockFrase.GetType().GetProperty("Confidence");
//propertyInfo.SetValue(mockFrase, Confidence.High);
Instead, using reflection on the real object solved the problem for me:
var frase = new RecognitionPhrase();
PropertyInfo propertyInfo = frase.GetType().GetProperty("Confidence");
propertyInfo.SetValue(frase, Confidence.High);

The correct way of using UnitOfWork in Repository Pattern

I'm trying to follow a tutorial on using the unit of work and repository pattern on MSDN but I've stumbled at the below:
private UnitOfWork unitOfWork = new UnitOfWork();
"This code adds a class variable for the UnitOfWork class. (If you were using interfaces here, you wouldn't initialize the variable here; instead, you'd implement a pattern of two constructors"
Basically, I need to call my UnitOfWork class in my LogController without actually using the above code as I'm using an interface? How is this possible? I'm not sure what it means by 'two constructors'.
Any advice would be appreiciated
In your class you define
Private IUnitOfWork _unitOfWork = null;
And you have one constructor which accepts an IUnitOfWork so the caller can pass in an implementation:
Public MyClass (IUnitOfWork unitOfWork) {
_unitOfWork = unitOfWork;
}
And you have another which does not, but knows how to go and find which implementation to create. Either it can use a default implementation, or it can go to some config file you've written to define which type to use, etc.
Within the MyClass you still call _unitOfWork.whateverMethod()

Test calls to private methods with moq

I have the following method I need to test with Moq. The problem is that each method called in the switch statement is private, including the PublishMessage at the end. But this method (ProcessMessage) is public. How can I test this so that I can ensure the calls are made depending on the parameter? Note that I'm not testing the private methods, I just want to test the "calls". I'd like to mock these private methods and check if they are called using Setup, but Moq does not support mocking private methods.
public void ProcessMessage(DispenserMessageDataContract dispenserMessage)
{
var transOptions = new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted };
using (var scope = new TransactionScope(TransactionScopeOption.RequiresNew, transOptions))
{
switch (dispenserMessage.Type)
{
case DispenserMessageType.AckNack:
UpdateAckNackMessageQueue(dispenserMessage);
break;
case DispenserMessageType.FillRequest:
CreateFillRequestMessageQueue(dispenserMessage);
break;
case DispenserMessageType.FillEvent:
UpdateFillEventMessageQueue(dispenserMessage);
break;
case DispenserMessageType.RequestInventory:
CreateRequestInventoryMessageQueue(dispenserMessage);
break;
case DispenserMessageType.ReceiveInventory:
CreateReceiveInventoryMessageQueue(dispenserMessage);
break;
}
scope.Complete();
}
PublishMessage(dispenserMessage);
}
You will have to change those private methods to atleast protected virtual to mock them and then use mock.Protected to mock them(http://blogs.clariusconsulting.net/kzu/mocking-protected-members-with-moq/). You can't mock private methods.
Moq (and few other frameworks) uses Castle Project's DynamicProxy to generate proxies on the fly at run-time so that members of an object can be intercepted without modifying the code of the class. That interception can only be done on public virtual and protected virtual methods.
See below URL for more information:
http://www.castleproject.org/projects/dynamicproxy/
You could extract the private method in another class and make them public, then mock those with Moq and verify that they have been called.
Moq is for mocking properties and methods declared in interfaces and or abstract properties and methods in classes.
The idea behind Moq-testing is that you test the interactions between your class-under-test and the rest of the world (its dependencies). Moq does this by creating a "mocked" implementation of the interface or a derivative of the abstract class with the abstract methods implemented.
Moq cannot override existing implementation like your private methods. This is not how Moq works.
Either you should test "ProcessMessage" with all possible input and expected output or you should refactor your class to delegate the calls to interface methods that you can mock with Moq. Testing private methods is a bad concept anyway. They are kept private for a reason, which is to hide the implementation such that it can change at will.
I prefer to add additional class (*Helper) and move on all my private methods to public. Then you can easily test your methods directly. I didn't find more elegant way to do that.
In some cases, you may need to alter the behavior of private method inside the class you are unit testing. You will need to mock this private method and make it return what needed for the particular case. Since this private method is inside your class under test then mocking it is little more specific. You have to use spy object.
Spy object
A spy is a real object which mocking framework has access to. Spied objects are partially mocked objects. Some their methods are real some mocked. I would say use spy object with great caution because you do not really know what is happening underneath and whether are you actually testing your class or mocked version of it.
public class PowerMockDemo
{
public Point callPrivateMethod() {
return privateMethod(new Point(1, 1));
}
private Point privateMethod(Point point) {
return new Point(point.getX() + 1, point.getY() + 1);
}
}
Then you will mock the Spy object
Hope that will help you,
Best wishes

asp.net mvc3, why do I need to constructors for my controller class

I am learning asp.net mvc3. one example I found online is to show me how to use IOC.
public class HomeController : Controller
{
private IHelloService _service;
public HomeController():this(new HelloService())
{}
public HomeController(IHelloService service)
{
_service = service;
}
}
there are two constructors in this example. I understand the second one. the first one I understand what that for, but to me, it seems like extra code, you will never need it.
can someone please explain to me whats the point to add the first constructor.
public HomeController():this(new HelloService())
{}
When the MVC Framework instantiates a controller, it uses the default (parameter-less) constructor.
By default, you are injecting a concrete IHelloService implementation. This will be used when a user navigates to the action.
Unit Tests would use the overload and pass in the mock IHelloService implementation rather than calling the default constructor.
It can be useful if you don't use a dependency injection framework that injects this for you. In this way you never have to manually inject the object, the object will handle that by itself.
The second constructor is, of course, useful to inject custom objects when unit testing.
Normally one would need to do this:
IFoo foo = new Foo();
IBar bar = new Bar(foo);
When your constructor creates a default object you can just do this:
IBar bar = new Bar();
Bar will then create a Foo and inject it into itself.

Resources