nunit and moq interview questions

In case of multi-layered applications, each layer must be tested separately for their functionality, so that the consuming layer gets the correct result. There are various approaches to verify the correctness of each layer in the application. Generally, a manual testing approach is followed for testing an application. But in case of manual testing, a lot of efforts goes in while creating testing scripts and soon the time taken for creating testing scripts becomes a major cost factor. Because of the time and cost involved in manual testing, automated testing is recommended. The advantages of automated testing is that the test code is always available with the application code and can be executed at any time to verify the code changes.

ASP.NET MVC is now being used prominently for developing multi-layer web applications. MVC itself indicates that we have Model layer for Business operations, Controller layer for handling actions and View layer for UI with DataBinding. The architecture of MVC by default encourages multiple teams to simultaneously work on multiple layers. This makes it possible to test each layer separately. Visual Studio already provides support for testing frameworks where we can perform Unit Testing of our source code. The Developer himself can do this very easily.

As seen in the , the Source code can be tested using Testing Frameworks. The Testing framework applies Testing Attributes and uses Asserts to define the Test environment and test result respectively. The Test Runner provides testing statistics to inform the status of the test, whether it succeeded or failed. We can make use of various testing frameworks like Nunit, xUnit.Net, etc. for performing Unit tests. In the article we will be making use of NUnit.

NUnit is a Unit Testing framework for all .NET languages and brings in a xUnit style of testing. It provides several attributes which can be used during tests. In our application, we will be making use of the following attributes:

TestFixtureAttribute – is applied on the class that contains test methods. This helps the Test Runner to run tests from this class.

Test – this attribute is applied on a public method containing Test. The method is present inside the class applied with TestFixtureAttribute. This informs the Test Runner to run this method as test.

More information on NUnit can be obtained over here. Visual Studio provides you with the necessary NUnit references from NuGet Package manager as shown in the following figure:

NUnit Interview Questions for freshers experienced :-

1. What Is NUnit ?

NUnit is a unit-testing framework for all .Net languages. Initially ported from JUnit, the current production release, version 2.2, is the fourth major release of this xUnit based unit testing tool for Microsoft .NET. It is written entirely in C# and has been completely redesigned to take advantage of many .NET language features, for example custom attributes and other reflection related capabilities. NUnit brings xUnit to all .NET languages.

2. What is the Advantages of NUnit ?

  • NUnit is an automated unit-testing framework for all .Net languages.
  • Initially ported from JUnit, which is a unit testing framework for Java applications.
  • It is written entirely in C# and has been completely redesigned to take advantage of many .NET language features.
  • NUnit brings xUnit to all test are written in .NET supported language e.g. C#, VC, VB.NET, J# etc.
  • NUnit is an open source free to use with your .NET projects.
  • NUnit provides a class library which includes some classes, features and methods to help you write test scripts.
  • NUnit provides user interface application to execute the test scripts and displays result
  • NUnit does not create any test scripts by itself. We have to write test scripts and use NUnit tools and classes to make the unit testing easier and display the result as a success or failure.
  • 3. What is the Features of NUnit ?

    (1) Assertions :-

    Assertions are central to unit testing in any of the xUnit frameworks, and NUnit is no exception. NUnit provides a rich set of assertions as static methods of the Assert class. The most commonly used assertions.

  • Equality Asserts
  • Identity Asserts
  • Comparison Asserts
  • Type Asserts
  • Condition tests
  • Utility methods
  • StringAssert
  • CollectionAssert
  • FileAssert
  • Equal Constraint (Available NUnit 2.4)
  • Same As Constraint (Available NUnit 2.4)
  • Condition Constraints (Available NUnit 2.4)
  • Comparison Constraints (Available NUnit 2.4)
  • Type Constraints (Available NUnit 2.4)
  • String Constraints (Available NUnit 2.4)
  • Collection Constraints (Available NUnit 2.4)
  • Compound Constraints (Available NUnit 2.4)
  • Custom Constraints (Available NUnit 2.4)
  • (2) Attributes :-

    NUnit and Moq Interview questions

    Implementing of Mock Test: – You can implement mocking by using open source mocking frameworks like Rhino mocks, MOQ etc. For example if we want to Mock the email class method by using MOQ tool we need to write the below code.

    In our previous post, we learn how to set up environment for our NUnit Project. In this post, well learn how to write our first NUnit Test Case with Example in .NET / C#. We have two projects CustomerOrderService project which is a class library and CustomerOrderService.Tests project which is a NUnit test project.

    Once the DLL compilation is done go to program files – nunit and click on nunit. Now the nunit user interface will open. Click on file – open project and select your test DLL. Once you select your DLL you will get a screen as shown below. On the right hand side you can see your test class with test function which has the test case.

    Unit testing means testing the smallest unit of code such as method or class in isolation to other methods and classes in the application.But if we have a method which creates an object of some other class or calls another method then this could make the method difficult to unit test.

    The primary differences you see when setting up unit tests for ASP.NET MVC Controller are: You must manually set attributes of the Controller class to be what you expect them to be (e.g. Unit Test Scenario #4, where we set ModelState.IsValid to be false).

    Handling Cookies from unit tests. Testing Action Filters (MVC). Using CSV file for data driven tests. – We can multiple data items to a unit test to check for all possible data scenarios. Detailed code commenting of web and test projects to make code clear and self-explanatory for developers. Comments detailing MOQ framework itself.

    The Unit test is code where we test all the code paths of the methods and ensure that the results are as expected. Mock object is the object that can act as a real object but can be controlled in test code. It is very useful in generating the objects which are used in test method. You can view or download source code from here.

    Let’s take a look at a simple example of unit testing in which we create a new ASP.NET MVC application with Unit Testing. Step 1 − Open the Visual Studio and click File → New → Project menu option. A new Project dialog opens. Step 2 − From the left pane, select Templates > Visual C# > Web.

    NUnit is a unit-testing framework for all.Net languages. Initially ported from JUnit, the current production release, version 3, has been completely rewritten with many new features and support for a wide range of.NET platforms. NUnit is a part of the.NET Foundation The NUnit Project is a member of the.NET Foundation.

    NUnit is a unit-testing framework for all.Net languages. NUnit is Open Source software and NUnit 3.0 is released under the MIT license. This framework is very easy to work with and has user friendly attributes for working. You can check the details of Nunit from here.

    So NUnit.TestAdapter exists for that purposes. NUnit itself implements the testing frameworks and its contracts. So you need to add a NuGet reference to it to write unit test cases and have them compiled. Only compiled projects along with the test adapter can then be consumed by Visual Studio.

    In the above example, NUnit checks that the return value of the method is equal to the expected result provided on the attribute. TestCaseAttribute supports a number of additional named parameters: Author sets the author of the test. Category provides a comma-delimited list of categories for this test.

    Open Test Explorer. To open Test Explorer, choose Test > Test Explorer from the top menu bar (or press Ctrl + E, T). Run your unit tests by clicking Run All (or press Ctrl + R, V). After the tests have completed, a green check mark indicates that a test passed.

    In this post, well learn how to write our first NUnit Test Case with Example in .NET / C#. We have two projects CustomerOrderService project which is a class library and CustomerOrderService.Tests project which is a NUnit test project. First create two classes Customer and Order and one enum CustomerType in CustomerOrderService project.

    Unit Tests

    All set now and we are ready to write unit tests for ProductController. We’ll write test to perform all the CRUD operations and all the action exit points that are part of ProductController.

    Our ProductService in BusinessServices project contains a method named GetAllProducts (), following is the implementation,

    Let me explain the code step by step. We start code by creating an instance of ProductController and initialize the Request property of controller with new request message stating calling http method as GET and initialize the RequestUri with base hosted service URL and appended with actual end point of the method. Initializing RequestUri is not necessary in this case but will help you if you test actual service end point. In this case we are not testing actual endpoint but the direct controller method.

    HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() line adds default httpconfiguration to HttpConfigurationKey necessary for controller instance instantiation.

    _response = productController.Get(); line calls the Get() method of controller that fetches all the products from dummy _products list. Since the return type of the method was an http response message, we need to parse it to get the JSON result sent from the method. All the transactions from API’s should ideally happen in form of JSON or XML only. This helps client to understand the response and its result set. We de-serialize the object we got from _response using NewtonSoft library into a list of products. That means the JSON response is converted to List for better accessibility and comparison. Once done with JSON to List object conversion, I have put three asserts to test the result.

    Assert.AreEqual(_response.StatusCode, HttpStatusCode.OK); line checks the http status code of the response, the expected is HttpStatusCode.OK.

    Second assert i.e. Assert.AreEqual(responseResult.Any(), true); checks that we have got the items in the list or not. Third assert is the actual confirmation assert for our test that compares each product from the actual product list to the returned product list.

    We got both the list, and we need to check the comparison of the lists, I just pressed F5 and got the result on TestUI as,

    This shows our test is passed, i.e. the expected and returned result is same.

    This unit test verifies if the correct result is returned if we try to invoke GetProductById() method of product controller.

    I have used a sample product id “2” to test the method. Again we get the result in JSON format inside HttpResponse that we de-serialize. First assert compares for the status code and second assert makes use of AssertObject class to compare the properties of the returned product with the actual “mobile” named product having product id as 2 from the list of products.

    NUnit provides flexibility to even test the exceptions. Now if we want to unit test the alternate exit point for GetProductById() method i.e. an exception so what should we do? Remember it was easy to test the alternate exit point for business services method because it returned null. Now in case of exception, NUnit provides an attribute ExpectedException. We can define the type of exception expected to be returned from the method call. Like if I make a call to the same method with wrong id, the expectation is that it should return an exception with ErrorCode 1001 and an error description telling “No product found for this id.”.

    So in our case the expected exception type is ApiDataException (got it from controller method).Therefore we can define the Exception attribute as [ExpectedException(“WebApi.ErrorHelper.ApiDataException”)]

    And call the controller method with wrong id. But there is an alternate way to assert the exception. NUnit also provides us flexibility to assert the exception by Assert.Throws. This statement asserts the exception and returns that particular exception to the caller.Once we get that particular exception we can assert it with its ErrorCode and ErrorDescription or on whatever property you want to.

    In the above code, I have commented out the Exception attribute approach and followed the alternate one.

    I called the method with wrong id (that does not exists in our product list) in the statement,

    The above statement expects ApiDataException and stores the returned exception in “ex”.

    Now we can assert the “ex” exception properties like ErrorCode and ErrorDescription with the actual desired result.

    Another exit point for the same method is that if request for a product comes with an invalid it then an exception is thrown. Let’s test that method for this scenario,

    I passed an invalid id i.e. -1 to the controller method and it throws an exception of type ApiException with ErrorCode equal to HttpStatusCode.BadRequest and ErrorDescription equal to “bad Request…”.

    i.e. Passed. Other tests are very much of same kind like I explained.

    All the above mentioned tests are self-explanatory and are more like how we tested BusinessServices.the idea was to explain how we write tests in WebAPI. Let’s run all the tests through NUnit UI.

    1. Step 1: Launch NUnit UI. I have already explained how to install NUnit on the windows machine. Just launch the NUnit interface with its launch icon,

    2. Step 2 : Once the interface opens, click on File -> New Project and name the project as WebAPI.nunit and save it at any windows location.

    3. Step 3: Now, click on Project-> Add Assembly and browse for ApiController.Tests.dll (The library created for your unit test project when compiled)

    4. Step 4: Once the assembly is browsed, you’ll see all the unit tests for that test project gets loaded in the UI and are visible on the interface.

    5. At the right hand side panel of the interface, you’ll see a Run button that runs all the tests of Api controller. Just select the node ApiController in the tests tree on left side and press Run button on the right side.

    Once you run the tests, you’ll get green progress bar on right side and tick mark on all the tests on left side. That means all the tests are passed. In case any test fails, you’ll get cross mark on the test and red progress bar on right side.

    But here, all of our tests are passed.

    I’ll give just an idea of what integration tests are and how can we write it. Integration tests doesn’t run in memory. For WebAPI’s the best practice to write integration test is when the WebAPI is self hosted.You can try writing integration test when you host an API, so that you you get an actual URL or endpoint of the service you want to test.The test is performed on actual data and actual service. Let’s proceed with an example. I have hosted my web api and I want to test GetAllProducts() method of WebAPI.My hosted URL for the particular controller action is http://localhost:50875/v1/Products/Product/allproducts.

    Now I know that I am not going to test my controller method through dll reference but I want to actually test its endpoint for which I need to pass an authentication token because that end point is secured and can not be authorized until I add a secure token to the Request header. Following is the integration test for GetAllProducts().

    In above code I have initialized the client with running service’s base URL i.e. http://localhost:50875. After initialization I am setting a default request header to call my login endpoint of Authentication controller to fetch valid token.Once the user logs in with his credentials he get a valid token. To read in detail about security refer my article on security in web api. I have passed base 64 string of my credentials username :Akhil and password:Akhil for basic authentication.Once request gets authenticated, I get a valid token in _response.Headers that I fetch and assign to _token variable and add to client’s default header with this line of code,

    Then I am calling the actual service URL from the same client,

    And we get the result as success. Follow the screen shots.

    Step1: Get Token

    We got the token : 4bffc06f-d8b1-4eda-b4e6-df9568dd53b1. Now since this is a real time test.This token should get saved in database. Let’s check.

    Step2 : Check database

    We got the same token in database.It proves we are testing on real live URL.

    Step3 : Check ResponseResult

    Here we got the response result with 6 products where first product id is 1 and product name is “Laptop”. Check the database for complete product list,

    We get the same data. This proves our test is a success.

    Likewise you can write more integration tests.

    C# unit test mock interface

    In the unit tests, instead of creating an object of the old MockPlayerDataMapper, and passing it into the Player.CreateNewPlayer function, we will use Moq to create the mock object. Line 24 is how Moq creates an object that implements the IPlayerDataMapper interface.

    Mock – A mock object is a fake object in the system that decides whether or not a unit test has passed or failed. A mock starts out as a Fake until its asserted against. A mock starts out as a Fake until its asserted against.

    Fundamentals of Unit Testing: Understand Mock Object in Unit Testing Fundamentals of Unit Testing: Unit Testing of IOC Code We know that, dependency injection is one of the important parts of application development when we want to do de-coupled architecture.

    The C# language was not designed with unit testing in mind. Thats why its really hard to inject mock dependencies without a tremendous clutter of pointless interfaces or virtual methods. Perhaps someone will soon invent a language that is easy to unit-test.

    Mocking Frameworks (Moq, NSubstitute, Rhino Mocks, FakeItEasy, and NMock3) are used to create fake objects. We can stub, i.e., completely replace the body of member and function. It is used to isolate each dependency and help developers in performing unit testing in a concise, quick, and reliable way.

    Mock objects allow you to mimic the behavior of classes and interfaces, letting the code in the test interact with them as if they were real. This isolates the code you’re testing, ensuring that it works on its own and that no other code will make the tests fail.


    How do I mock a class in NUnit?

    Mocking is a process where dependencies are replaced by controlled replacements that simulate the behavior of the real dependencies. NUnit is a unit testing framework for . NET languages, and Moq is the most popular mocking framework for . NET.

    Why NUnit is used?

    The three key steps to using mock objects for testing are:
    1. Use an interface to describe the object.
    2. Implement the interface for production code.
    3. Implement the interface in a mock object for testing.

    How NUnit is used in unit testing?

    The NUnit Framework caters to a range of attributes that are used during unit tests. They are used to define Test -Fixtures, Test methods, ExpectedException, and Ignore methods.

    Related Posts

    Leave a Reply

    Your email address will not be published.