mardi 5 février 2019

Mocking an object initialised inside a method under test

I am trying to test a class which instatiates another class within it. It is the instatinated class call I want to mock.

Is this possible or is they a way around it/ simpler way I am missing?

Below I have written up a simpler example which still has the same problemts as my main code.

public interface my_interface
{
    int returns_25();
}

public class class_i_want_to_mock : my_interface
{
    public int returns_25()
    {
        // TEST SHOULD FAIL SO NEED MOCK TO PASS THE CASE
        return 7645745;
    }
}

In another namespace (it has access):

public class class_to_test
{
        public static int returns_25()
        {
            class_i_want_to_mock _tempClass= new class_i_want_to_mock ();

            // Will return 7645745 unless moq changes return value
            int _temp_int = _tempClass.returns_25()
            return _temp_int;
        }
}

My test (which fails):

    [Test]
    public void test_returns_25()
    {
        // Mock 
        Mock<my_interface> myMock = new Mock<my_interface>();
        myMock.Setup(m => m.returns_25()).Returns(25);

        // Act
        int return_number = class_to_test.returns_25();

        // Assert
        Assert.AreEqual(25, return_number);
    }

Aucun commentaire:

Enregistrer un commentaire