How to unit test a method that is having multiple object creation in switch statement? How to Mock them?

mockito mock new object inside method
how to mock a method call inside another method
how to mock new object creation using mockito
mockito spy
mockito tutorial
mockito mock method
mockito mock new object inside method without powermock
mockito documentation

Another question is if there is any better way to write this method?

Public decimal CalculateTotalPrice(List<product> items)
{
    decimal totalPrice = 0.m;

    foreach(Product p in items)
    {
        if(p.Offer == "")
            calc = new DefaultCalc();
        else if(p.Offer == "BuyOneGetOneFree")
            calc = new BuyOneGetOneFreeCalc();
        else if(p.Offer == "ThreeInPriceOfTwo")
            calc = new ThreeInPriceOfTwoCalc()

        totalPrice += calc.Calculate(p.Quantity, p.UnitPrice);
    }
    return totalPrice;
}

Unit testing Java switch - case logic, it looks like you have some method whose logic branches on the insurance type. switch statements, you should see a coherent InsuranceType domain object all the places where you switch on InsuranceType -- instead, you just create a test each of your InsuranceType s in isolation without a whole lot of mocking  Pester allows you to automate the testing of PowerShell scripts. It can test the output of a function as you develop it by validating simple data (scalars) and arrays, Pester allows you to focus on the one function you want to test by using 'mocking' to fake all the other functions and Cmdlets, It also uses Parameterized tests save you from writing essentially the same test over and over with


Constructors can not be mocked (at least with free mocking frameworks).

Write tests without mocking as far as your tests run fast and test case setup is not very very complicated.

In your particular case you should be able to write tests without mocking.

Prepare data

var products = new List<Product>
{
    new Product { Quantity = 10, UnitPrice = 5.0m, Offer = "" },
    new Product { Quantity = 2, UnitPrice = 3.0m , Offer = "BuyOneGetOneFree" },
    new Product { Quantity = 3, UnitPrice = 2.0m , Offer = "ThreeInPriceOfTwo" },
}

// prepare expected total
var expected = 57.0m; // 10 * 50.0 + 1 * 3.0 + 2 * 2.0

// Run the test
var actual = CalculateTotalPrice(products);

actual.Should().Be(expected); // pass Ok.

With this approach tests will not depend on implementation details. You will be able to freely play with designs without rewriting tests every time you change your implementation logic.

Mockito mock examples, In unit test case at the time of mocking I am sending an Employee object but when invoking the business logic method, it is creating different Employee object​  There are numerous benefits to writing unit tests; they help with regression, provide documentation, and facilitate good design. However, hard to read and brittle unit tests can wreak havoc on your code base. This article describes some best practices regarding unit test design for your .NET Core and .NET Standard projects.


The other answers are technically fine, but I would suggest one thing:

    if(p.Offer == "")
        calc = new DefaultCalc();
    else if(p.Offer == "BuyOneGetOneFree")
        calc = new BuyOneGetOneFreeCalc();
    else if(p.Offer == "ThreeInPriceOfTwo")
        calc = new ThreeInPriceOfTwoCalc()

should absolutely go into its own method/scope/whatever.

You are mapping a string to a specific calculator. That should happen in one place, and one place only. You see, first you do that here. Then some method method comes around that needs the same mapping. So you start duplicating.

What is Mocking?, With fakerandom in place, we call our method and test the output. annoyance we can do without, so unittest.mock provides a cleaner approach using patch. an import path string and provides us with a Mock object that it has patched in. assertEqual(rv, 0.5) In this case, the mock object created by patch is passed as an  Then you have multiple [Test] methods each asserting different things you would expect to be true, given the object's current state. Each [Test] method is named after the thing it is asserting, except perhaps it might be named after the concept instead of just an English readout of the code.


How to mock method with hard coded object?, With fakerandom in place, we call our method and test the output. annoyance we can do without, so unittest.mock provides a cleaner approach using patch. an import path string and provides us with a Mock object that it has patched in. assertEqual(rv, 0.5) In this case, the mock object created by patch is passed as an  In this situation, the concept of mocking comes into the picture. The mock object will mimic the original object, so that we can carry on with the development process. There are many mocking frameworks on the market which we can use for our mock object creation. Moq is one of them. It is free and simple to use.


Python GUI Programming with Tkinter: Develop responsive and , In case your are not familiar with JUnit please check the following JUnit Tutorial. To use Mockito in a Maven project you have to add it as dependency. Mockito provides several methods to create mock objects: getUniqueId(), 43); } // demonstrates the return of multiple values @Test public void  This is the default behaviour, but it can be overridden in different ways. For example you can assign a value to an attribute in the Mock by:. Assign it directly, like you’d do with any Python


Python GUI Programming, [5] recommend to create one mock agent for every role of the tested agent), Test case compares records with the plan to find out whether the agent's behavior is correct. this approach is that it is too much inspired by its ''object oriented'' ancestor. there is no uncertainty about the result of the actual operation (method). Mock takes several optional arguments that specify the behaviour of the Mock object: spec: This can be either a list of strings or an existing object (a class or instance) that acts as the specification for the mock object. If you pass in an object then a list of strings is formed by calling dir on the object (excluding unsupported magic