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

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.

Related

Mockito object always giving a NullPointer exception

This is the class that I want to test.
open class Foo(bar :Bar){
fun someMethod() = bar.anotherMethod()
}
And I have a builder class to get Foo mock instance since Mockito cant mock constructor arguments.
open class FooBuilder{
fun makeFoo(bar:Bar) = Foo(bar)
}
Here is my approach to make the mock Objects and verify.
var fooBuilderMock = mock(FooBuilder::class)
var barMock = mock(Bar::class)
var fooMock = mock(Foo::class)
Mockito.`when`(fooBuilderMock.makeFoo(barMock)).thenReturn(fooMock)
fooMock.someMethod()
Mockito.verify(barMock, Mockito.times(1)).anotherMethod()
I am getting a null pointer exception on barMock object.
Don't use the Builder, there is no need for it. Additionally, don't mock the class that you are trying to test. If you do it, your test makes no sense.
class FooTest {
private val barMock = mock(Bar::class)
private lateinit var foo: Foo
#BeforeEach
fun setUp() {
MockitoAnnotations.initMocks(this)
foo = Foo(barMock)
}
#Test
fun `Your test name`() {
// Arrange
Mockito.`when`(barMock.anotherMethod()).thenReturn(// whatever it should return)
// Act
fooMock.someMethod()
// Assert
Mockito.verify(barMock, Mockito.times(1)).anotherMethod()
}
}
As a side note consider taking a look at mockk and using it instead of Mockito. It is implemented in kotlin and thus supports it since day 1. With it, your test would look similar but follow more the kotlin "style":
class FooTest {
#MockK
private lateinit var barMock = mock(Bar::class)
private lateinit var foo: Foo
#BeforeEach
fun setUp() {
MockitoAnnotations.initMocks(this)
foo = Foo(barMock)
}
#Test
fun `Your test name`() {
// Arrange
every { barMock.anotherMethod() } returns //whatever it should return
// Act
foo.someMethod()
// Assert
verify(exactly = 1) { barMock.anotherMethod() }
}
}

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

Invalid setup on a non-overridable member:

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.

How to Unit test Web API calling Method

I am calling a Web Api method inside my Repository layer. Can anyone suggest how to test it using Mocking
If you want to mock the call to a Web API method you will have to abstract the code that is calling it.
So abstract it:
public interface IMyApi
{
MyObject Get();
}
and then you could have a specific implementation of this interface that is using an HttpClient to call the actual API:
public class MyApiHttp: IMyApi
{
private readonly string baseApiUrl;
public MyApiHttp(string baseApiUrl)
{
this.baseApiUrl = baseApiUrl;
}
public MyObject Get()
{
using (var client = new HttpClient())
{
client.BaseAddress = this.baseAddress;
var response = client.GetAsync('/api/myobjects').Result;
return response.Content.ReadAsAsync<MyObject>().Result;
}
}
}
Now your repository layer will simply take this abstraction as constructor argument:
public class Repository: IRepository
{
private readonly IMyApi myApi;
public Repository(IMyApi myApi)
{
this.myApi = myApi;
}
public void SomeMethodThatYouWantToTest()
{
var result = this.myApi.Get();
...
}
}
Next in your unit test it's trivial to mock the access to the API using your favorite mocking framework. For example your the unit test with NSubstitute might look like this:
// arrange
var myApiMock = Substitute.For<IMyApi>();
var sut = new Repository(myApiMock);
var myObject = new MyObject { Foo = "bar", Bar = "baz" };
myApiMock.Get().Returns(myObject);
// act
sut.SomeMethodThatYouWantToTest();
// assert
...

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.