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

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);

Related

AutoFixture/AutoMoq: Unable to Create Instance (`BadImageFormatException`)

Below is a minimal example of the problem I am currently encountering:
using System.Net.WebSockets;
using AutoFixture;
using AutoFixture.AutoMoq;
using FluentAssertions;
using Xunit;
...
[Fact]
public void Test1()
{
var fixture = new Fixture().Customize(new AutoMoqCustomization() { ConfigureMembers = true });
var sut = fixture.Create<WebSocket>();
sut.Should().NotBeNull();
}
[Fact]
public void Test2()
{
var fixture = new Fixture().Customize(new AutoMoqCustomization() { ConfigureMembers = true });
var sut = new Mock<WebSocket>().Object;
fixture.Inject(sut);
sut.Should().NotBeNull();
}
...
When I run the first test, I get the following exception:
AutoFixture.ObjectCreationExceptionWithPath : AutoFixture was unable to create an instance from Moq.Mock`1[System.IO.Stream] because creation unexpectedly failed with exception. Please refer to the inner exception to investigate the root cause of the failure.
Inner exception messages:
System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)
The second test succeeds.
I would like to be able to create an instance of a class using AutoFixture which takes a WebSocket as a constructor parameter, without the need to inject a mock object first (ultimately, so that I can use an AutoMoqData attribute, and get rid of some boilerplate). Have I got any misusage or misunderstanding going on here, or would this be better placed as a GitHub issue? In the interim, is there anything I can do to work around this issue?
You observe this issue because of the AutoFixture's factory discovery strategy. When you try to create an object of an abstract type, AutoFixture still inspects the type to find a static factory method to activate the object. In your particular case, the WebSocket type contains such methods, so some of them is used. It looks like it doesn't work well with auto-generated input values, so fails with an exception.
You can customize AutoFixture, to always mock the WebSocket type:
fixture.Register((Mock<WebSocket> m) => m.Object);
Just tested with the latest versions of products (AutoFixture 4.5.0, Moq 4.10.0) and it works like a charm.

ICollection Count method fails in ASP.NET MVC 4

I have a ICollection of Projects in my user class
public ICollection<Project> Projects { get; set; }
When I try to render the count of projects in my view, it gives an error
<h2>You have #Model.Projects.Count() projects....</h2>
Any help appreciated.
ICollection doesn't have a Count method, it has a Count property. You are probably getting confused with the LINQ Count extension method which is supported on an IEnumerable interface.
Just remove the parenthesis at the end of the Count call i.e.
<h2>You have #Model.Projects.Count projects...</h2>
I think I figured out what the issue was here. I added a constructor in my user class to handle the null reference exception
public User()
{
this.Roles = new List<Role>();
this.Projects = new List<Project>();
}
This did the trick.
And ofcourse I called count without the paranthesis
In general, I've found it useful to write default constructors of every type, so that when stepping through a project like this I can visually see when each one is called. Not having a copy constructor or something similar can mask odd issues like this and make debugging infinitely frustrating.

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

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.

Unity Container passing runtime constructor parameters

I have two constructors, the first works fine as follows:
public ESite(Func<IOrg> unityOrgFactory)
{
this.OrFactory = unityOrgFactory;
this.Kid = Guid.Empty;
}
_IoC.RegisterType<IESite, ESite>();
IESite eSite = boClass.IoC.Resolve<IESite>();
Now, I need to pass in a key at runtime so I add a constructor as usual:
public ESite(Func<IOrg> unityOrgFactory, Guid kid)
{
this.OrFactory = unityOrgFactory;
this.Kid = kid;
}
Syntax for this registration and resolve usage? I've tried several InjectionConstructor variants but can't get it right...I'm missing something. After several search-and-try rounds, time to ask! I have read several posts on related topics...
Thanks for tips!
GG
A reasonable workaround (not necessarily the best answer) is to disencumber the constructor by moving the injected parameters to an InjectionMethod
Register:
// Use InjectionMethod Initializer to free up constructors. http://msdn.microsoft.com/en-us/library/ff953186(v=pandp.50).aspx new InjectionMethod("Initialize", typeof(Database), "CustomerServices")
_IoC.RegisterType<IESite, ESite>(
new InjectionMethod("Initialize", typeof(Func<IOrg>))
);
Use:
//http://msdn.microsoft.com/en-us/library/ff953186(v=pandp.50).aspx
[InjectionMethod]
public void Initialize(Func<IOrg> unityOrgFactory)

TypeError: Error #1034: Type Coercion failed: cannot convert Object#1456c7b9 to mx.messaging.messages.IMessage

Im trying to connect a Flash client to BlazeDS. There has been some success with this from others using the vanilla BlazeDS setup. However I'm using the new Spring BlazeDS Integration from springsource and running aground.
The flash client actually seems to be working in that I can see the correct data in the body of the returned object, but for some reason unknown it fails casting as an IMessage. It fails in PollingChannel.as on this line with the subject line error
var messageList:Array = msg.body as Array;
for each (var message:IMessage in messageList) <--
On application load I register a whole bunch of classes like so
registerClassAlias( "flex.messaging.messages.RemotingMessage", RemotingMessage );
registerClassAlias("mx.messaging.messages.IMessage", IMessage);
etc..
my code is basically
var channelSet:mx.messaging.ChannelSet = new mx.messaging.ChannelSet();
var channel:mx.messaging.channels.AMFChannel = new AMFChannel("my-amf", "http://localhost:8400/SpringA/messagebroker/amf");
channelSet.addChannel(channel);
var consumer:mx.messaging.Consumer = new Consumer();
consumer.channelSet = channelSet;
consumer.destination = "simple-feed";
consumer.subscribe();
consumer.addEventListener(MessageEvent.MESSAGE, test);
private function test(event:IMessage)
{
trace("msg..");
// breakpoint never makes it here
}
I have a flex client which works 100% with same destination/channel.
The error in the title means that you, for some reason, got an object that is not implementing or extending the IMessage interface, therefore the loop can not cast it in this part:
for each (var message:IMessage in messageList){
Either you should somehow make sure that you don't add anything that is not extending or implementing IMessage, or check if the variable IS actually ext./imp. it. Also - if you want to do that, you will have to change the for each like this:
for each (var obj in messageList){
if (obj is IMessage){
var message:IMessage = obj as IMessage;
// DO STUFF HERE
}
}
Add this Object mapping:
registerClassAlias("flex.messaging.io.ObjectProxy", ObjectProxy);
If on your Java VO objects you have overridden the hashcode() method, this situation could happen.
Remove the hashcode() override (if you are able to).
See my blog for the backstory on how I discovered this. http://squaredi.blogspot.com/2013/12/remoting-landmine-without-stack-trace.html
I had the same error when trying to send an actionscript object to the backend. My problem was that my c# equivalent object was missing an public parameterless constructor.

Resources