I am trying to invoke a private method in my unit test to initialize a value. I know I can use java reflections to invoke private methods, but I am wondering if I can use Apache MethodUtils to invoke a private method:
org.apache.commons.lang3.reflect.MethodUtils
Any suggestion would be much appreciated.
Private methods can be invoked using forceAccess = true:
MethodUtils.invokeMethod(ObjectName, true, "MethodName");
Related
I have been working on .NET Core FirebaseAdminSdk. I want to write unit tests for my own services that are using FirebaseApp class.
FirebaseApp is a sealed class and there is not any interface to moq it.
Is there any way to mock FirebaseApp instance?
private readonly Mock<IFirebaseApp> firebaseApp = new Mock<IFirebaseApp>();
I need an interface something like this.
It's generally not a good idea to try to mock sealed classes like FirebaseApp, because they are designed to be used in a specific way and mocking them can lead to unexpected behavior and make it difficult to test your code correctly.
Instead of trying to mock FirebaseApp, you can use a technique called "dependency injection" to make it easier to test your code. Here's how it works:
Create an interface that defines the methods and properties that you need from FirebaseApp. For example:
public interface IFirebaseApp
{
string Name { get; }
FirebaseAppOptions Options { get; }
Task<string> GetAccessTokenAsync(bool forceRefresh);
void Delete();
}
Modify your code to accept an instance of IFirebaseApp through its
constructor or a property, rather than creating a new instance of
FirebaseApp directly. This is called "dependency injection".
In your unit tests, create a mock implementation of IFirebaseApp
using a mocking framework like Moq. Then pass an instance of the
mock to your code when you create an instance of your service.
This will allow you to easily control the behavior of FirebaseApp in your tests, and make it easier to test different scenarios.
I have an extension method which is used to read a particular claim from the current ClaimsPrincipal. But I also need to check this value against a list of items which I have in the appsettings.json.
I had this working by using a ConfigurationBuilder() to read the appsettings directly in much the same way as the startup does, although instead of using
.SetBasePath(Directory.GetCurrentDirectory())
as I do in the startup, I was using
.SetBasePath(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location))
Which although isn't pretty, works fine.
However, when the Unit tests are run none of the following get me to where the appsettings are
Directory.GetCurrentDirectory()
Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
and I cannot see a way of getting the IHostingEnvironment or something similar into the extension method to read out the appsettings, or indeed to ditch the ConfigurationBuilder() and get at IOptions in the extension method, in such a way that the unit test and the running code will work correctly.
I assume there must be a way of doing this? Although I expect that I should simply not be trying at all and lift the check against the list of items into another class entirely...
Putting business logic that may ever require dependencies into static methods is not recommended. This makes it difficult to inject dependencies into them. Options are few:
Redesign the static method into a service so dependencies can be injected through the constructor. (Recommended)
public class Foo : IFoo
{
private readonly IOptions<FooOptions> optionsAccessor;
public Foo(IOptions<FooOptions> optionsAccessor)
{
this.optionsAccessor = optionsAccessor ??
throw new ArgumentNullException(nameof(optionsAccessor));
}
public void DoSomething()
{
var x = this.optionsAccessor;
// Same implementation as your static method
}
}
Inject the dependencies as parameters of the extension method.
public static void DoSomething(this object o, IOptions<FooOptions> optionsAccessor)
{
// Implementation
}
Redesign the static method to be a facade over an abstract factory like this example.
Somewhere I have read that private methods aren't supposed to be tested. Your tests should only care about the real thing - your public API. If your public methods work, then the private ones they call will also work
So is it not necessary to test private methods, but consider below example
private
def valid_extension?(file_path)
extension = file_type(file_path)
extension.in?(%w(csv xls xlsx)) ? true : false
end
the above private method returns whether the file extension is valid or not, so what if someone changes my private method like this
private
def valid_extension?(file_path)
true
end
it will always give me valid extension
So, is it not necessary to test private methods also.
Since we cannot access private method outside class, so how to test the private methods using rspec-rails.
As per Rspec, Rails: how to test private methods of controllers? , you may use
#your_instance_name.instance_eval{ valid_extension }
I have the following legacy class that I want to add some unit tests to using Xunit and Moq
The psuedo code for the class I want to test is below:-
public class Foo : IFoo
{
public StatusResposne GetStatus(string jobId)
{
.
.
var response = GetRequest(doc, targeturl);
.
.
}
private XDocument GetRequest(XDocument doc, string url)
{
}
}
Now i want to test GetStatus but im order to do that i need to mock the GetRequest method.
Can anyone suggest the easiest way to do this?
Cheers
Unit testing ought to be black-box testing, because otherwise your tests will be too brittle: every time you change an implementation detail, you'll need to fix all the tests that break.
When you view Foo as a black box, only GetStatus is visible. The fact that there's a private GetRequest method is irrelevant. Someone else might come by tomorrow and decide to refactor the GetStatus implementation in such a way that the GetRequest method is no longer used - perhaps that method will no longer be there.
You should test the observable behaviour of GetStatus, instead of attempting to test implementation details.
i need to mock the GetRequest method
That's not possible. You can only mock interfaces and accessible virtual methods.
Do you have access to the source code?
One way could be to make GetRequest protected virtual and override it in some inherited class and use this class for the unit tests.
Better would be to move this method to some other class and use it as a dependency.
I was coding test cases for an angular application using jasmine. But many internal methods are declared as private in the services.
Example:
App.service('productDisplay', function(){
var myPrivate = function(){
//do sth
}
this.doOfferCal = function(product, date){
//call myPrivate
//do sth too
return offer;
}
});
Using jasmine it straightforward to code test for "doOfferCal" but I want to write unit test for myPrivate too.
How can I do it?
Thanks in advance.
Thanks jabko87.
In addition, if you want to pass the the arguments use the below example:
const myPrivateSpy = spyOn<any>(service, 'transformNative').and.callThrough();
myPrivateSpy.call(service, {name: 'PR'});
Note: Here service is the Class, transformNative is the private method and {name: 'PR'} passing an object argument
Is there a specific reason you wish to test your private methods?
By testing doOfferCal(), you're implicitly testing that myPrivate() is doing the right thing.
Though this is for RailsConf, Sandi Metz has a very good talk on what should be tested.
Achan is 100% right, but if you really need to call private method in your tests (what should be never :-) ) you can do it by:
var myPrivateSpy = spyOn(productDisplayService, "myPrivate").and.callThrough();
myPrivateSpy.call();
If you want to call your private method you just have to do it like this:
component["thePrivateMethodName"](parameters);
Where component is your service class or component class.
To test inner functions I call the outer function that calls the inner function and then vary my input according to what the inner function requires. So, in your case you would call productDisplay and vary your input based upon what myPrivate needs and then verify that you have the expected output. You could also spy on myPrivate and test things that way using .havebeencalledwith or .andcallthrough.