Assert and Verify both fail - c#

Please see the code below:
[TestClass]
public class UnitTest1
{
Moq.Mock<ISayGoodMorning> GoodMorningMock;
[TestInitialize]
public void init()
{
GoodMorningMock = new Moq.Mock<ISayGoodMorning>();
GoodMorningMock.Setup(x => x.GoodMorning()).Returns(Test());
}
[TestMethod]
public void TestMethod1()
{
GoodMorningMock.Verify(x => x.GoodMorning(), Times.Once());
Assert.AreEqual(g.SayGreeting(), "Hola");
}
public string Test()
{
return "Hola";
}
}
The assert and the verify fail. Why is that? Here is the code that is tested:
namespace ClassLibrary1
{
public class SayGoodMorning : ISayGoodMorning
{
public string GoodMorning()
{
return "Good Morning";
}
}
public interface ISayGoodMorning
{
string GoodMorning();
}
}
namespace ClassLibrary2
{
public class Greeting
{
public string SayGreeting()
{
ISayGoodMorning s = new SayGoodMorning();
return s.GoodMorning();
}
}
}

First the subject under test needs to be refactored to inject the dependency to allow a mock to be used when testing. Either via constructor or method injection. (Explicit Dependencies Principle)
This example uses constructor injection
namespace ClassLibrary2 {
public class Greeting {
private readonly ISayGoodMorning speaker;
public Greeting(ISayGoodMorning speaker) {
this.speaker = speaker;
}
public string SayGreeting() {
return speaker.GoodMorning();
}
}
}
Next the test needs to be restructured so that the Verify is done after exercising the method under test;
[TestClass]
public class UnitTest1 {
Mock<ISayGoodMorning> GoodMorningMock;
[TestInitialize]
public void init() {
//Arrange
GoodMorningMock = new Mock<ISayGoodMorning>();
GoodMorningMock.Setup(_ => _.GoodMorning()).Returns(Test());
}
[TestMethod]
public void TestMethod1() {
//Arrange cont'd
var g = new ClassLibrary2.Greeting(GoodMorningMock.Object);
var expected = "Hola";
//Act
var actual = g.SayGreeting();
//Assert
GoodMorningMock.Verify(_ => _.GoodMorning(), Times.Once());
Assert.AreEqual(expected, actual);
}
public string Test() {
return "Hola";
}
}

Related

C# Moq method in abstract class

Can someone show me how I can mock the result of a method in a base abstract class? See the very basic sample code below to demonstrate the problem and I need to mock the “GetAge()” method’s result. See the commented line at the end with the ending "<----- FIX here" where I think need to add the fix.
Customer Service
public interface ICustomerService
{
string GetCustomerDetailsSrv(int age);
}
public class CustomerService : ICustomerService
{
public string GetCustomerDetailsSrv(int age)
{
return $"Name: John Doe. Age: {age}";
}
}
Base Controller
public abstract class MyBaseController : ControllerBase
{
public virtual int GetAge()
{
return 7;
}
}
Customer Controller
public class CustomerController : MyBaseController
{
private readonly ICustomerService _customerSrv;
public CustomerController(ICustomerService customerSrv)
{
_customerSrv = customerSrv;
}
[HttpGet]
public string GetCustomerDetails()
{
var age = GetAge();
var result = _customerSrv.GetCustomerDetailsSrv(age);
return result;
}
}
Customer Controller Test
[TestClass]
public class CustomerControllerTest
{
private readonly CustomerController _controller;
private readonly Mock<ICustomerService> _mockSrv;
public CustomerControllerTest()
{
_mockSrv = new Mock<ICustomerService>();
_controller = new CustomerController(_mockSrv.Object);
}
[TestMethod]
public void TestGet()
{
//Arrange
int mockAge = 11;
string expectedResult = $"Name: Alice Smith. Age: {mockAge}";
// _controller.Setup(Controller => Controller.GetAge()).Returns(mockAge); <----- FIX here
_mockSrv.Setup(repo => repo.GetCustomerDetailsSrv(mockAge)).Returns(expectedResult);
//Act
var actualResult = _controller.GetCustomerDetails();
//Assert
Assert.IsTrue(actualResult == expectedResult);
}
}
I think the following code achieves what you want.
Creating a Mock from a CustomerController allows the setup the virtual method GetAge while still being able to use the GetCustomerDetails method from the CustomerController class.
[TestClass]
public class CustomerControllerTest
{
private readonly Mock<CustomerController> _mockController;
private readonly Mock<ICustomerService> _mockSrv;
public CustomerControllerTest()
{
_mockSrv = new Mock<ICustomerService>();
_mockController = new Mock<CustomerController>(() => new CustomerController(_mockSrv.Object));
}
[TestMethod]
public void TestGet()
{
//Arrange
int mockAge = 11;
string expectedResult = $"Name: Alice Smith. Age: {mockAge}";
_mockController.Setup(Controller => Controller.GetAge()).Returns(mockAge);
_mockSrv.Setup(repo => repo.GetCustomerDetailsSrv(mockAge)).Returns(expectedResult);
//Act
var actualResult = _mockController.Object.GetCustomerDetails();
//Assert
Assert.IsTrue(actualResult == expectedResult);
}
}

Compare Action<T>

I have a service class as below:
public class MyService
{
private readonly IMyDependency _myDependency;
public MyService(IMyDependency myDependency)
{
_myDependency = myDependency;
}
public void MyHandler(string param)
{
// work
}
public void AnotherMethod()
{
_myDependency.DoWork(MyHandler);
}
}
How can I Unit Test that MyHandler has been given as a parameter of DoWork()?
Since you are using Moq, you can write test like this:
[TestMethod]
public void DoWorkWasCalledWithCorrectParameters()
{
var mock = new Moq.Mock<IMyDependency>();
var myService = new MyService(mock.Object);
myService.AnotherMethod();
// verify that method was called once and with correct parameter:
mock.Verify(x => x.DoWork(myService.MyHandler), Moq.Times.Once);
}

How to unit test constructor when using nested test classes

Assuming I have some logic in a class constructor that I wish to unit test, how would I structure it if I am using xUnit.net and nested test classes for each method?
using Xunit;
public class MyClass
{
public MyClass()
{
// Some logic to test
}
public int GetResult()
{
return 123;
}
}
public class MyClassFacts
{
// How to test MyClass constructor?
// Nested classes to test each of MyClass' methods
public class GetResult
{
[Fact]
public void IsCorrect()
{
var myClass = new MyClass();
int result = myClass.GetResult();
Assert.Equal(123, result);
}
// Other tests for MyClass.GetResult()...
}
}
You're already testing it in your IsCorrect() test technically but if you want an explicit test:
using Xunit;
public class MyClass
{
public MyClass()
{
// Some logic to test
}
public int GetResult()
{
return 123;
}
}
public class MyClassFacts
{
[Fact]
public void Ctor()
{
var myClass = new MyClass();
Assert.NotNull(myClass);
// Any other asserts you require
}
// Nested classes to test each of MyClass' methods
public class GetResult
{
[Fact]
public void IsCorrect()
{
var myClass = new MyClass();
int result = myClass.GetResult();
Assert.Equal(123, result);
}
// Other tests for MyClass.GetResult()...
}
}

Rhino mock AAA ExpectationViolationException

Getting Error while running rhinomock test method : Test method TestProject1.UnitTest2.TestMethod1 threw exception:
Rhino.Mocks.Exceptions.ExpectationViolationException: ITestInterface.Method1(5); Expected #1, Actual #0.
My code looks like:-
namespace ClassLibrary1
{
public interface ITestInterface
{
bool Method1(int x);
int Method(int a);
}
internal class TestClass : ITestInterface
{
public bool Method1(int x)
{
return true;
}
public int Method(int a)
{
return a;
}
}
}
And my test looks something like:-
using ClassLibrary1;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Rhino.Mocks;
namespace TestProject1
{
[TestClass]
public class UnitTest2
{
[TestMethod]
public void TestMethod1()
{
ITestInterface mockProxy = MockRepository.GenerateMock<ITestInterface>();
TestClass tc = new TestClass();
bool result = tc.Method1(5);
Assert.IsTrue(result);
mockProxy.AssertWasCalled(x => x.Method1(5));
}
}
}
Any help appreciated.
You expect ITestInterface.Method1 to be called, but it never does.
You don't use your mockProxy at all in the test code - you just create it and you create your own instance, but there's no relation between the two of them.
Your TestClass is not dependant upon any interface that you want to mock, similar example that does use the mock would be:
internal class TestClass
{
private ITestInterface testInterface;
public TestClass(ITestInterface testInterface)
{
this.testInterface = testInterface;
}
public bool Method1(int x)
{
testInterface.Method1(x);
return true;
}
}
[TestClass]
public class UnitTest2
{
[TestMethod]
public void TestMethod1()
{
ITestInterface mockProxy = MockRepository.GenerateMock<ITestInterface>();
TestClass tc = new TestClass(mockProxy);
bool result = tc.Method1(5);
Assert.IsTrue(result);
mockProxy.AssertWasCalled(x => x.Method1(5));
}
}
I think you should read more about using Rhino Mocks, e.g. Rhino Mocks AAA Quick Start?

Rhino mocks stub vs expect, always choosing first one why?

I went with this solution:
Stubbing a property twice with rhino mocks
but even when I change both of my Stubs to .Expect, the first Expect is winning out:
Here's the recreation in mono:
using System;
using NUnit.Framework;
using Rhino.Mocks;
namespace FirstMonoClassLibrary
{
[TestFixture]
public class TestingRhinoMocks
{
Sut _systemUnderTest;
IFoo _dependency;
[SetUp]
public void Setup()
{
_dependency = MockRepository.GenerateMock<IFoo>();
_dependency.Expect(x => x.GetValue()).Return(1);
_systemUnderTest = new Sut(_dependency);
}
[Test]
public void Test()
{
_dependency.Stub(x => x.GetValue()).Return(2);
var value = _systemUnderTest.GetValueFromDependency();
Assert.AreEqual(2, value); // Fails says it's 1
}
}
public interface IFoo
{
int GetValue();
}
public class Sut
{
private readonly IFoo _foo;
public Sut(IFoo foo)
{
_foo = foo;
}
public int GetValueFromDependency()
{
return _foo.GetValue();
}
}
}
you need to do the following:
[Test]
public void Test()
{
_dependency.BackToRecord();
_dependency.Expect(_ => _.GetValue).Return(2);
_dependency.Replay();
var value = _systemUnderTest.GetValueFromDependency();
value.ShouldBe(2); // Fails says it's 1
}

Categories