I would like to test a new function in a helper file.
function isProductionSite() {
return !(bool) preg_match('/admin|development/', request()->getHttpHost());
}
When I call this function in my test function I get my local address. Therefore I tried to mock the request()->getHttpHost.
public function testIsProductionSiteExpectFalse(): void
{
$request = Mockery::mock(Request::class);
$request->shouldReceive('getHttpHost')->once()->andReturn('admin.mydomain.de');
$this->assertFalse(isProductionSite());
}
In the Tets Function $request->getHttpHost() would now output admin.mydomain.de. But getHttpHost() from the function to be tested (isProductionSite()) gives me the correct host.
How can I set the HttpHost in the testcase so that the helper function outputs the manipulated host?
You're mocking an instance of $request but the instance being used by the function under test is not the mock, but presumably a global variable.
Dependencies should always be passed to the helper function. Just add $request as a parameter of isProductionSite.
Related
I have a class (class A) to which I define an extension function (A.extension()) inside a companion object of another class (class B) for a matter of organization.
On my tests I need:
To use a real class A instance .
To mock A.extension().
To use a mock instance of class B.
Using MockK-library I am not being able to mock that extension function successfully.
I've tried:
mockkObject(B.Companion) {
every { any<A>().extension() } returns whatIneed
}
result: Tries to run the unmocked version of the extension function.
mockkStatic(path.to.B.CompanionKt)
every { any<A>().extension() } returns whatIneed
Result: It does not find the Companion Object.
mockkStatic(A::extension) {
every { any<A>().extension() } returns whatIneed
}
Result: Compile error -> 'extension' is a member and an extension at the same time. References to such elements are not allowed.
Am I missing something regarding how to mock this ?
Am I doing something wrong in terms of code structuring that prevents this mocking to be possible?
Any help is appreciated.
This seems to be an impossible thing. I have tried this severally and it does not work.
Using Sinon stubs, I have successfully stubbed functions along the project, using the traditional stubbing syntax:
const permissionsStub = sinon.stub(invitation, 'update')
sinon.assert.calledOnce(permissionsStub)
Now I am trying to Stub a built-in function of NodeJS (findIndex, indexOf, etc..), without success, as it should be passed with the in the first argument of Sinon's stub() function call, and as that is a NodeJS's core function, what needs to be passed?
I have tried creating an empty stub and then assigning it directly to the function in the code, but I think there is a simpler way to try and spy/stub/mock built-in NodeJS functions.
I get this error by trying to pass a few arguments that might target it correctly, as it doesn't succeed mounting:
TypeError: Cannot read property 'returns' of undefined
How can I target those functions in a simpler way using Chai and Sinon?
So eventually I got it to work using the following code (rewire is being used to get to the inner unexported functions of the file):
const permissionIndex = invitation.__get__('permissionIndex')
permissionsStub.findIndex = () => {
return { id: 1 }
}
expect(permissionIndex(1, permissionsStub)).to.be.an('object')
expect(permissionIndex(1, permissionsStub)).to.have.deep.property('id', 1)
I have a method that is shown as below and this in turn call multiple private methods, that I won't be posting here.
#Bean
public CommandLineRunner registerStartersAndReaders(final Vertx vertx, final SpringVerticleFactory springVerticleFactory,
final SpringUtil springUtil, final GslConfig gslConfig) {
return args -> {
// Scan all the beans annotated with the #ElasticsearchBatchDataListener annotation.
List<Pair<Object, Method>> listenerMethods = springUtil.getListenerMethods();
// Deploy the starters per listener.
deployVerticle(listenerMethods, jsonConfig -> deployStarterVerticle(vertx, springVerticleFactory, jsonConfig), config);
// Deploy the reader verticles.
deployVerticle(listenerMethods, jsonConfig -> deployReaderVerticle(vertx, springVerticleFactory, jsonConfig), config);
setupTriggers(vertx, listenerMethods, config);
};
}
Then I have a test method for it :
#Test
public void registerStartersAndReadersTest() {
when(springUtil.getListenerMethods()).thenReturn(value);
CommandLineRunner runner = config.registerStartersAndReaders(vertx, springVerticleFactory, springUtil, config);
assertNotNull(runner);
}
Here, all the parameters passed into the method call are mocks. The problem is, when I run this test, it passes but it returns the value without getting into the private methods as it just returns 'args'.
Can someone please guide me, as to how I can make my test cover all the possible code. I am not supposed to change my code for the test.
I think you got confused with the lamba expression, and believe me it is very confusing in the beginning. But once you are fluent with it, it will be a breeze.
So here you got the instance of CommandLineRunner from method registerStartersAndReaders call, and your assertNotNull PASS as you have the not null instance, but until you call the run method of FunctionalInterface nothing will be executed.
Add runner.run(args) to execute the method(s) in your test case.
I come from python and I have been looking for a way to write yests in go. I have come across a few things on SO but they all seem very cumbersome and verbose for something that shpuld be needed all the time.
I am typing on mobile now, will add code later if needed...but for example...
say i have a function that calls smtp.Send somewhere in the middle. how can I easily test this function?
Say i have another one that hits some outside api (needs mocking) and then takes the response and calls something like ioutil.Readall()...how could i make my way through this test function and mock the call to the api and then pass some fake response data when Readall is called?
You can do it by using an interface. For example let's say you have an interface called Mailer:
type Mailer interface {
Send() error
}
Now you can embed a Mailer object into the function that calls the Send method.
type Processor struct {
Mailer
}
func (p *Processor) Process() {
_ = p.Mailer.Send()
}
Now in your test you can create a mock Mailer.
type mockMailer struct{}
//implement the Send on the mockMailer as you wish
p := &Processor{
Mailer: mockMailer,
}
p.Process()
when p.Process reaches the Send method it calls your mocked Send method.
I am trying to make a unit test on a very simple interface.
my interface is:
public interface Interface1
{
string retStr(string dd);
string retStr2(string dd,string fff);
}
this is the mock:
var myMoq = new Mock<Interface1>();
myMoq.Setup(d => d.retStr("David")).Returns("retStr");
Console.WriteLine(myMoq.Object.retStr("fdf").ToString());
I GOT runtime error: Object reference not set to an instance of an object.
and another error on implementation:
myMoq.Setup(d => d.retStr2(It.Is<string>(e=>e=="qqq"), It.IsAny<string>())).Returns("2 parameters");
Console.WriteLine(myMoq.Object.retStr2("fdf","wewew").ToString());
Why is it?
In your setup, you are setting the expectation that a specific string will be passed in (for example "David").
You are telling Moq, "Pass back "retStr" if the method invoked with the string "David", otherwise return a default value (for string, null). Because of this, when you do a .ToString() on the result of the method, the object is null.
The same thing applies to the second example.
In order to make a more general return value, use It.IsAny<string>() when setting up a method. Or, do as you expect in the test and send in "David" when you call the method.