moq System.Web.Mvc.HtmlHelper Partial method - moq

does anyone knows how to mock HtmlHelper.Partial?
I've created my own htmlhelper class and one of the feature of the said helper class is to return an MvcHtmlString of htmlHelper.Partial.
Example:
public static MvcHtmlString ScriptEditorFor(this HtmlHelper<ViewModel> htmlHelper,
Identifiers.PainAssessmentVariables painVariable)
{
return htmlHelper.Partial("test");
}
I'm getting null reference exception when I try to moq test this

You can't. Partial is a static method (an extension method), and moq can't mock static methods.
You have to eihter hide the call to Partial behind an interface, or use a mocking framework that is capable of mocking static methods.

Related

Mock methods of a class not given by DI

I have a class I am trying to test. The class constructor has a class that is injected and another class that is initialized in the constructor. The second class comes from an external source.
public class MyClass
{
private readonly ILogger<MyClass> _logger;
private readonly MavlinkParse _mavlink;
public MyClass(ILogger<MyClass> logger)
{
_logger = logger;
_mavlink = new MavlinkParse();
}
}
Later I have a method where I call the _mavlink methods based on a condition. I want to somehow mock the methods, or better yet just "spy" on them and know which was called.
The method:
public SomeMethod(input)
{
if(cond)
return _mavlink.method1(lots of params);
return _mavlink.method2(lots of params);
}
I know how to mock the logger using xunit and moq. What I am stuck on is how to test SomeMethod().
I come from the angular world, where I could easily solve this issue with a spy, and expect(method1Spy).toHaveBeenCalled() would be perfect. I would also be able to settle for the idea of having method1() return a hard-coded value, ignoring params, and check that that came through
How can I achieve this effect in c# dotnet core using xunit and moq?

Please help to explain a strange combination of Lombok's #AllArgsConstructor and spring's #RestController

I'm working on a spring project from our customer.
Below is the code for controller
#Log4j2
#RestController
#AllArgsConstructor
#RequestMapping(path = "/api/theapi")
#Api(value = "Description for the API")
public class TheAPIController {
private final ModelMapper modelMapper;
private final ObjectMapper objectMapper;
private final TheDemoService demoService;
...other code for controller
}
Below is the code for Service:
#Service
public class TheDemoService{ ... }
I was so surprise about 2 things:
Question 1: Why we need to use #AllArgsConstructor from project Lombok?
As per my understanding, Spring provide #RestController that Spring runtime container will initialize an Instance for our Controller. So that, having a constructor for our Controller seems like an invalid approach for using Spring Inversion of Control, is this correct?
Question 2. Because of using #AllArgsConstructor, somehow, the instance for demoService is to be injected
But again, I surprise because the code of Controller does not have #Autowired in combine with demoService.
In the actual code, there is no #Autowired for "private final TheDemoService demoService".
Hence, I could think of a possibility there, is that because of Lombok's #AllArgsConstructor would inject an instance of our TheDemoService via a constructor of
TheAPIController, I could not reason anything about this logic.
It's Invalid approach, no need for defining constructor for RestController
It's implicitly auto wiring the service
if a class, which is configured as a Spring bean, has only one constructor, the Autowired annotation can be omitted and Spring will use that constructor and inject all necessary dependencies.
To sum up #AllArgsConstructor can/should be removed

what is the relation between GenricServlet and ServletConfig?

A GenericServlet is a type of ServletConfig, also GenericServlet has a ServletConfig. What is logic in this? How should I understand this?
public abstract class GenericServlet implements Servlet, ServletConfig, Serializable {
private static final long serialVersionUID = 1L;
private transient ServletConfig config;
..
}
The ServletConfig is an interface and is implemented by services in order to pass configuration information to a servlet when it is first loaded.
GenericServlet implements ServletConfig. It's not a subclass of ServletConfig. Understand the difference between a subclass and interface.
GenericServlet class implements Servlet, ServletConfig and Serializable interfaces. It provides the implementation of all the methods of these interfaces except the service method.
GenericServlet class can handle any type of request so it is protocol-independent.
You may create a generic servlet by inheriting the GenericServlet class and providing the implementation of the service method.
Visit here for more

Set ViewBag property in the constructor of a ASP.NET MVC Core controller

My theme has some sort of breadcrumb. The controller is always the category. To avoid repeat myself, I want to set it in the constructor of the controller for all actions like this:
class MyController:Controller{
public MyController() {
ViewBag.BreadcrumbCategory = "MyCategory";
}
}
When I access ViewBag.BreadcrumbCategory in the layout-view, its null. In a Action it works:
class MyController:Controller{
public IActionResult DoSomething() {
ViewBag.BreadcrumbCategory = "MyCategory";
}
}
I'm wondering that setting a ViewBag property is not possible in a constructor? It would be annoying and no good practice to have a function called on every action which do this work. In another question using the constructor was an accepted answear, but as I said this doesn't work, at least for ASP.NET Core.
There is an GitHub issue about it and it's stated that this is by design. The answer you linked is about ASP.NET MVC3, the old legacy ASP.NET stack.
ASP.NET Core is written from scratch and uses different concepts, designed for both portability (multiple platforms) as well as for performance and modern practices like built-in support for Dependency Injection.
The last one makes it impossible to set ViewBag in the constructor, because certain properties of the Constructor base class must be injected via Property Injection as you may have noticed that you don't have to pass these dependencies in your derived controllers.
This means, when the Controller's constructor is called, the properties for HttpContext, ControllerContext etc. are not set. They are only set after the constructor is called and there is a valid instance/reference to this object.
And as pointed in the GitHub issues, it won't be fixed because this is by design.
As you can see here, ViewBag has a dependency on ViewData and ViewData is populated after the controller is initialized. If you call ViewBag.Something = "something", then you it will create a new instance of the DynamicViewData class, which will be replaced by the one after the constructor gets initialized.
As #SLaks pointed out, you can use an action filter which you configure per controller.
The following example assumes that you always derive your controllers from Controller base class.
public class BreadCrumbAttribute : IActionFilter
{
private readonly string _name;
public BreadCrumbAttribute(string name)
{
_name = name;
}
public void OnActionExecuting(ActionExecutingContext context)
{
base.OnActionExecuting(context);
var controller = context.Controller as Controller;
if (controller != null)
{
controller.ViewBag.BreadcrumbCategory = _name;
}
}
}
Now you should be able to decorate your controller with it.
[BreadCrumb("MyCategory")]
class MyController:Controller
{
}
I have the same issue and solve it overriding the OnActionExecuted method of the controller:
public override void OnActionExecuted(ActionExecutedContext context)
{
base.OnActionExecuted(context);
ViewBag.Module = "Production";
}
Here is a better way to do this for .NET Core 3.x, use the ResultFilterAttribute:
Create your own custom filter attribute that inherits from ResultFilterAttribute as shown below:
public class PopulateViewBagAttribute : ResultFilterAttribute
{
public PopulateViewBagAttribute()
{
}
public override void OnResultExecuting(ResultExecutingContext context)
{
// context.HttpContext.Response.Headers.Add(_name, new string[] { _value });
(context.Controller as MyController).SetViewBagItems();
base.OnResultExecuting(context);
}
}
You'll need to implement the method SetViewBagItems to populate your ViewBag
public void SetViewBagItems()
{
ViewBag.Orders = Orders;
}
Then Decorate your Controller class with the new attribute:
[PopulateViewBag]
public class ShippingManifestController : Controller
That's all there is to it! If you are populating ViewBags all over the place from your constructor, then you may consider creating a controller base class with the abstract method SetViewBagItems. Then you only need one ResultFilterAttribute class to do all the work.

Best way to pass reference of injected dependency in spring controller

I have a Spring portlet controller class. In this class, there is a dependency like this:
#Autowired
protected ServiceClass someService;
#Autowired
protected ApplicationContext context;
From the controller, there is a utility class being called like this:
UtilityClass.loadStaticData((WebApplicationContext)context);
Inside UtilityClass, I have:
public static synchronized boolean loadStaticData(WebApplicationContext context){
ServiceClass someService = (ServiceClass) context.getBean("someService");
...
}
My question is: Is there any advantage to getting the handle of the someService in such a complicated way? We could have just passed the reference 'someService' from Controller class #1 to the UtilityClass. The author is no longer available so I am asking here.
This is basically what dependency injection tries to avoid: getting a dependency from the container instead of having the dependency injected by the container.
This utility class should be a Spring bean, where the service would be injected. And you could then inject this utility bean inside the controller.

Resources