Invalid setup on a non-overridable member: - unit-testing

I'm trying to test the function GetcallEntityBycallEntity (Guid callId) with Mock library.
this function calls another class that does not implement any interface.
protected virtual CallFacade CallFacade()
{
return new CallFacade();
}
public Note GetCallEntityByCallEntity(Guid CallEntity)
{
myCall= null;
**CallFacade** callFacade = Get CallFacade();
if (CallEntity!= Guid.Empty)
{
myCall = callFacade.GetCallByEntityId(CallEntity);
}
return myCall;
}
CallFacade Not is an Interface
in my test:
[TestInitialize]
public void TestInitialization()
{
IoCMocks.Initialize();
CommonCallFacadeMock = new CommonCallFacadeMock();
}
public void GetCallEntityByNoteEntity_GetCall_ReturnValidCall()
{
//Arrange
CallmyNote = GetmyCall(); //private method. == Call.CreateCall();
//Stubs
CommonCallFacadeMock.MockCallFacade.Setup(x => x.GetCallByEntityId(ExistingCallEntity)).Returns(myCall);
//Action
var obtained = CommonCallFacadeMock.GetCallEntityByCallEntity(ExistingCallEntity);
CommonCallFacadeMock.MockCallFacade.Verify(x => x.GetCallByEntityId(It.IsAny<Guid>()), Times.Once());
}

You get this error message because MOQ can mock only interfaces, abstract methods or properties on abstract classes, virtual methods or properties on concrete classes.
You have to mark method GetCallByEntityId as virtual.
There is an old discussion in "Moq Discussions" google group about virtual methods.

Related

How to unit test a method which has CompletedFeature<UserDefinedObject>.supplyAsync(()-> someMethodWithReturn())) using Mockito?

I have a controller class with a method something() which makes calls to two different methods of the same class and merge the result of two calls.
class Controller{
...
public UDC doSomething(){
CompletableFuture<UDC> feature1 = CompletableFuture.supplyAsync(()-> {this.doOther()}).exceptionally(ex -> {return new SomeException();});
CompletableFuture<UDC> feature2 = CompletableFuture.supplyAsync(()-> {this.doSomeOther()}).exceptionally(ex -> {return new SomeException();});
...
return feature1.combine(feature2).get();
}
...
}
I don't think you should use Mockito to mock CompletableFuture here, any of them...
In the test, treat the Controller's doSomething functionality as a black box that given some input returns UDC.
Now, it's possible that doOther and/or doSomeOther call some external code that should be mocked. In this case the Controller looks probably something like this:
class Controller {
private final SomeExternalDependency dependency1;
public Controller(SomeExternalDependency dependency1) {
this.dependency1 = dependency1;
}
private UDC doOther() {
...
dependency1.foo();
...
}
private UDC toSomeOther() {
...
dependency1.bar();
...
}
}
In this case in the test you can mock out the dependency1 with mockito as usual:
class MyTest {
#Test
public void doSomething() {
SomeExternalDependency dep = Mockito.mock(SomeExternalDependency.class);
// specify the expectations
Controller controller = new Controller(dep);
controller.doSomething();
}
}

Using RhinoMocks, how can I assert that one of several methods was called?

Consider the following service interfaces:
public interface IServiceA
{
void DoSomething(string s);
void DoSomething(string s, bool b);
}
public interface IServiceB
{
void DoSomething();
}
The implementation of IServiceB depends on IServiceA like this:
public class ServiceB : IServiceB
{
private IServiceA _serviceA;
public ServiceB(IServiceA serviceA)
{
_serviceA = serviceA;
}
public void DoSomething()
{
_serviceA.DoSomething("Hello", true);
}
}
Ie. the dependency is injected in the constructor.
Now consider a unit test for the DoSomething() method. I wish to assert that one of the overloaded DoSomething-methods in IServiceA is called, but following a general principle that unit tests shouldn't know too much about the internal workings of the method being tested, I wish to be agnostic about which of the two overloads is called. Consider the following unit test:
[TestFixture]
public class ServiceBTests
{
[Test]
public void DoSomething_CallsServiceA()
{
var serviceAMock = MockRepository.GenerateMock<IServiceA>();
var service = new ServiceB(serviceAMock);
service.DoSomething();
// Problem: How to check if EITHER:
serviceAMock.AssertWasCalled(s => s.DoSomething(Arg<String>.Is.NotNull, Arg<bool>.Is.Anything));
// OR:
serviceAMock.AssertWasCalled(s => s.DoSomething(Arg<String>.Is.NotNull));
}
}
How can I assert that either one or the other of the two methods was called?
You could manually set a boolean flag like so:
[TestFixture]
public class ServiceBTests
{
[Test]
public void DoSomething_CallsServiceA()
{
var serviceAMock = MockRepository.GenerateMock<IServiceA>();
bool called = false;
serviceAMock.Stub(
x => x.DoSomething(Arg<String>.Is.NotNull, Arg<bool>.Is.Anything))
.WhenCalled(delegate { called = true; });
serviceAMock.Stub(x => x.DoSomething(Arg<String>.Is.NotNull))
.WhenCalled(delegate { called = true; });
var service = new ServiceB(serviceAMock);
service.DoSomething();
Assert.IsTrue(called);
}
}
I don't think this very useful though. Unit tests are concerned with anything that is observable from outside of the component boundaries. Method calls to mocks are part of that. In other words, it is OK if you test for a specific overload being called. After all, there must be a reason why you use that overload and not the other one.
If you really want the unit test to remain ignorant of the implementation, you wouldn't be allowed to assert method calls on mocks at all. That would be a severe restriction on your ability to write tests.

How can I create and use a partial stub (in MoQ) without being tied to the concrete implimentation?

I have code that uses MoQ to create a partial stub. I'd prefer to interact with the interface instead of the concrete implementation so that I won't have to modify the unit test if I have a different implementation of the interface.
So for example, I have a factory method such as:
private Mock<ISomeInterface> ISomeInterfaceStubFactory()
{
return new Mock<SomeConcreteImplementation>();
}
Here is the code that calls the method:
var partialStub = ISomeInterfaceStubFactory();
partialStub.Setup(m => m.MethodToStubOutThatMethodToTestCalls(It.IsAny<string>())).Returns(new List<SomeOtherObject>());
partialStub.CallBase = true;
var actualResult= partialStub.Object.MethodToTest();
Assert.That(actualResult, Is.EqualTo(expectedResult));
The problem is that when doing this is that ISomeInterfaceStubFactory won't compile. So I changed it to be like below, but doing this seems to break the partial stub. The actual implemented MethodToStubOutThatMethodToTestCalls operation gets called, not the stubbed version. Basically I'm trying to use polymorphism with the stub object. Is there anyway to do this? I'd like my unit test to not be highly coupled to the concrete implementation.
private Mock<ISomeInterface> ISomeInterfaceStubFactory()
{
return new Mock<SomeConcreteImplementation>.As<ISomeInterface>();
}
I think you are missing the point of mock objects. Returning a mock from a concrete implementation makes no sense. The idea is to have the class under test depend on some interface or abstract which you could mock.
Revising my answer per your clarification. I don't disagree with arootbeer, but I do want to understand what you are doing and why it doesn't work.
Here's a simple example of what I think you are trying to do. The test passes for me for both concrete implementations. Is this what you are trying to do, and does this example work for you?
Interface and classes:
using System;
namespace ClassLibrary1
{
public interface IFoo
{
string GetBaseString();
string GetExtendedString();
}
public class Foo_A : IFoo
{
public virtual string GetBaseString()
{
return "Foo_A";
}
public virtual string GetExtendedString()
{
return GetBaseString() + "_Bar";
}
}
public class Foo_B : IFoo
{
public virtual string GetBaseString()
{
return "Foo_B";
}
public virtual string GetExtendedString()
{
return GetBaseString() + "_Bar";
}
}
}
Unit test:
using System;
using Xunit;
using Moq;
namespace ClassLibrary1.UnitTests
{
public class Class1
{
[Fact]
public void GetExtendedString_ReturnsExtendedString()
{
var partialFoo = IFooFactory();
partialFoo.Setup(x => x.GetBaseString()).Returns("Foo");
partialFoo.CallBase = true;
string result = partialFoo.Object.GetExtendedString();
Assert.Equal("Foo_Bar", result);
}
private Mock<IFoo> IFooFactory()
{
return new Mock<Foo_A>().As<IFoo>();
//return new Mock<Foo_B>().As<IFoo>();
}
}
}

Is this an acceptable way to test MVVM-Light Toolkit Messages?

[TestMethod()]
public void ShowSetup_SendsMessage_WhenShowSetupCommandCalled()
{
//Arrange
Messenger.Reset();
MainViewModel target = new MainViewModel();
bool wasCalled = false;
Messenger.Default.Register<NotificationMessage>(this,"Settings",(msg) => wasCalled = true);
//Act
target.ShowSetupCommand.Execute(null);
//Assert
Assert.IsTrue(wasCalled);
}
I see there is an IMessenger interface and I tried to mock it and set Messenger.OverrideDefault to the mock like this:
var mock = new Mock<IMessenger>();
Messenger.OverrideDefault((Messenger)mock.Object);
But I got an invalid cast error. Is the OverrideDefault method not for that purpose or more likely I'm using it incorrectly.
Or would I have an interface for the classes that are receiving the messages and mock those? All I really want to test is that a RelayCommand sends a message when it is called.
I just started to look at this myself. I'm a little surprised that Messenger.OverrideDefault doesn't take an IMessenger as a parameter. You have to inherit Messenger.
I suppose you could create a class that internally uses your mock object and then do a Verify.
[Test]
public void ShowSetup_SendsMessage_WhenShowSetupCommandCalled() {
Messenger.Reset();
MaintenanceViewModel target = new MainViewModel();
IMessenger mockMessenger = MockRepository.GenerateMock<IMessenger>();
mockMessenger.Expect(m => m.Send("Settings"));
TestMessenger testMessenger = new TestMessenger(mockMessenger);
Messenger.OverrideDefault(testMessenger);
bool wasCalled = false;
Messenger.Default.Register<NotificationMessage>(this, "Settings", (msg) => wasCalled = true);
target.ShowSetupCommand.Execute(null);
mockMessenger.VerifyAllExpectations();
}
You may or may not need a stub on the Register method.
The TestMessenger class:
public class TestMessenger : Messenger {
private IMessenger _mockMessenger;
public TestMessenger(IMessenger mock) {
_mockMessenger = mock;
}
public override void Register<TMessage>(object recipient, bool receiveDerivedMessagesToo, Action<TMessage> action) {
_mockMessenger.Register<TMessage>(recipient, receiveDerivedMessagesToo, action);
}
public override void Register<TMessage>(object recipient, Action<TMessage> action) {
_mockMessenger.Register<TMessage>(recipient, action);
}
public override void Send<TMessage, TTarget>(TMessage message) {
_mockMessenger.Send<TMessage, TTarget>(message);
}
public override void Send<TMessage>(TMessage message) {
_mockMessenger.Send<TMessage>(message);
}
public override void Unregister<TMessage>(object recipient, Action<TMessage> action) {
_mockMessenger.Unregister<TMessage>(recipient, action);
}
public override void Unregister<TMessage>(object recipient) {
_mockMessenger.Unregister<TMessage>(recipient);
}
public override void Unregister(object recipient) {
_mockMessenger.Unregister(recipient);
}
}
Another approach that using constructor injection you can see in this answer. I think it's better to use constructor injection instead of using static Messenger.Default. It's more robust approach cause dependency injection providing natural seam with which you can easily substitute dependencies in unit tests. If you try to substitute static member call, then you rely on internal implementation that obviously can change.

How to mock a function call on a concrete object with Moq?

How can I do this in Moq?
Foo bar = new Foo();
Fake(bar.PrivateGetter).Return('whatever value')
It seems I can only find how to mock an object that was created via the framework. I want to mock just a single method/property on a concrete object I've created.
In TypeMock, I would just do Isolate.WhenCalled(bar.PrivateGetter).Returns('whatever value').
Any ideas?
You should use Moq to create your Mock object and set CallBase property to true to use the object behavior.
From the Moq documentation:
CallBase is defined as “Invoke base class implementation if no expectation overrides the member. This is called “Partial Mock”. It allows to mock certain part of a class without having to mock everything.
Sample code:
[Test]
public void FailintgTest()
{
var mock = new Moq.Mock<MyClass>();
mock.Setup(m => m.Number).Returns(4);
var testObject = mock.Object;
Assert.That(testObject.Number, Is.EqualTo(4));
Assert.That(testObject.Name, Is.EqualTo("MyClass"));
}
[Test]
public void OKTest()
{
var mock = new Moq.Mock<MyClass>();
mock.Setup(m => m.Number).Returns(4);
mock.CallBase = true;
var testObject = mock.Object;
Assert.That(testObject.Number, Is.EqualTo(4));
Assert.That(testObject.Name, Is.EqualTo("MyClass"));
}
public class MyClass
{
public virtual string Name { get { return "MyClass"; } }
public virtual int Number { get { return 2; } }
}
Only TypeMock Isolator (and perhaps Moles) can perform these stunts. Normal dynamic mock libraries can only mock virtual and abstract members.
Moles can also replace private methods as long as the types on the signature are visible. So in this case, it would look like this:
MFoo bar = new MFoo { // instantiate the mole of 'Foo'
PrivateGetterGet = () => "whatever value" // replace PrivateGetter {get;}
};
Foo realBar = bar; // retrive the runtime instance
...
If you are looking for more information on Moles, start with the tutorials at http://research.microsoft.com/en-us/projects/pex/documentation.aspx.