I have following setup
A.CallTo(() => fakeChargeService
.CreateAsync(A<ChargeCreateOptions>._, A<RequestOptions>._, A<CancellationToken>._))
.Throws<StripeException>((se) => stripeException);
and then I assert
var msg = await Assert.ThrowsAsync<StripeException>(async () => await mediator.Send(command, CancellationToken.None));
which eventually executes this piece of code
var policyResult = await Policy.Handle<StripeException>(x => x.ShouldRetry())
.WaitAndRetryAsync(new[]
{
TimeSpan.FromSeconds(0.5),
TimeSpan.FromSeconds(1),
TimeSpan.FromSeconds(2),
})
.ExecuteAndCaptureAsync(async () => await this.chargeService.CreateAsync(options, null, cancellationToken));
and here I get error
Assert.Throws() Failure
Expected: typeof(Stripe.StripeException)
Actual: typeof(FakeItEasy.Configuration.FakeConfigurationException): The faked method has the signature (Stripe.ChargeCreateOptions, Stripe.RequestOptions, System.Threading.CancellationToken), but throws was used with (Stripe.StripeException).
I am not sure what is it that I am doing wrong. Any help would be appreciated
You seem to be specifying the wrong signature in your Throws. CreateAsync takes (Stripe.ChargeCreateOptions, Stripe.RequestOptions, System.Threading.CancellationToken), but Throws was used with (Stripe.StripeException).
See the second example in Throwing Exceptions:
// Pass up to 4 original call argument values into the method that creates the exception.
A.CallTo(() => fakeShop.NumberOfSweetsSoldOn(A<DateTime>._))
.Throws((DateTime when)=>new InvalidDateException(when + " is in the future"));
Note that the signature of the lambda and the called method match.
You should update your lambda to match the proper signature. Or better yet, just replace with
.Throws<StripeException>(stripeException)
since there doesn't appear to be any reason to lazily throw, based on the snippet of code you provided.
Related
Event i trying to flutter test, i get issue's invalid argument, in other case i explain same method to testing and result running as well, but i don't what a mockito mean at the issue's cause in other case i success with same method, let see my fetch test with mockito :
testing
test('should return list of tv/on_the_airs when response code is 200 ',
() async {
// arrange
when(mockHttpClient.get(Uri.parse('$BASE_URL/tv/top_rated?$API_KEY')))
.thenAnswer((_) async => http.Response(
'{"page": 1,"results": [ {"backdrop_path": "/4sSzTvk200BQyYjRJq69mLwE9xG.jpg","first_air_date": "2018-04-25","genre_ids": [16,35,18,10759],"id": 79141,"name": "Scissor Seven","origin_country": ["CN"],"original_language": "zh","original_name": "刺客伍六七","overview": "Seeking to recover his memory, a scissor-wielding, hairdressing, bungling quasi-assassin stumbles into a struggle for power among feuding factions.","popularity": 76.07,"poster_path": "/A39DWUIrf9WDRHCg7QTR8seWUvi.jpg","vote_average": 8.8,"vote_count": 457},],"total_pages": 125,"total_results": 2496}',
200));
// act
final result = await dataSource.getTopRatedTvSeriess();
// assert
expect(result, tTvSeriesList);
});
then i have error:
Invalid argument (string): Contains invalid characters.: "{\"page\": 1,\"results\": [ {\"backdrop_path\": \"/4sSzTvk200BQyYjRJq69mLwE9xG.jpg\",\"first_air_date\": \"2018-04-25\",\"genre_ids\": [16,35,18,10759],\"id\": 79141,\"name\": \"Scissor Seven\",\"origin_country\": [\"CN\"],\"original_language\": \"zh\",\"original_name\": \"刺客伍六七\",\"overview\": \"Seeking to recover his memory, a scissor-wielding, hairdressing, bungling quasi-assassin stumbles into a struggle for power among feuding factions.\",\"popularity\": 76.07,\"poster_path\": \"/A39DWUIrf9WDRHCg7QTR8seWUvi.jpg\",\"vote_average\": 8.8,\"vote_count\": 457},],\"total_pages\": 125,\"total_results\": 2496}"
I'm doing Flutter Clean Architecture TDD course from closely 20days. I'm writing unit test of Stream (mapEventToState) here is my Test code :
test(
'should emit [Error] when the input is invalid',
() async {
// arrange
when(mockInputConverter!.stringToUnsignedInteger(SIGNED_STRINGS))
.thenReturn(Left(InvalidInputFailure()));
// assert later
final expected = [
// The initial state is always emitted first
NumberTriviaEmpty(),
NumberTriviaError(message: INVALID_INPUT_FAILURE_MESSAGE),
];
expectLater(bloc!.state, emitsInOrder(expected));
// act
bloc!.add(GetTriviaForConcreteNumber(tNumberString));
},
);
Just forget all about (when), because It's fine I've mocked all classes and simply return a Left of Either which is obviously a Failure. So the problem rise in expected data, I just created list of expected and passed it inside the method the "expectLater" in order "emitsInOrder".
My Implementation code of Stream is is here :
#override
Stream<NumberTriviaState> mapEventToState(NumberTriviaEvent event,) async* {
if (event is GetTriviaForConcreteNumber) {
final inputEither =
inputConverter.stringToUnsignedInteger(event.numberString);
yield* inputEither!.fold(
(failure) async* {
yield NumberTriviaError(message: INVALID_INPUT_FAILURE_MESSAGE);
},
// Although the "success case" doesn't interest us with the current test,
// we still have to handle it somehow.
(integer) => throw UnimplementedError(),
);
}
The [ Error ] I have put in the Title isn't completed because It's a little bit long I'm sharing it here please take a look upon It what actually I'm doing wrong.
Expected: should do the following in order:
• emit an event that NumberTriviaEmpty:<NumberTriviaEmpty()>
• emit an event that NumberTriviaError:<NumberTriviaError(Invalid Input - The number must be a positive integer or zero.)>
Actual: NumberTriviaEmpty:<NumberTriviaEmpty()>
Which: was not a Stream or a StreamQueue
I have done all these the same, what it expect from me but still it's throwing this exception. I stuck in this error about 4 days I search everywhere but I didn't find any fix, Kindly If I'm doing something wrong just throw your recommendation in the comment section or Answer. Thank you :)
In addition to changing 'bloc!.state' to 'bloc' (per QuangNV and ouflak), try also changing the 'async' in your test to the asynchronous generator, 'async*', to match to the code used in your Stream implementation.
test(
'should emit [Error] when the input is invalid',
() async* {
// arrange
I used another way by using the bloc_test: ^8.0.0 package and the flutter_bloc: ^7.0.0
blocTest<NumberTriviaBloc, NumberTriviaState>(
'should emits [LoadingState, ErrorState(InputConvert failure..)] when add event [getConcreteNumberTrivia] with invaildString ',
build: () => numberTriviaBloc,
setUp: () => when(mockInputConverter.stringToUnsignedInteger(any))
.thenReturn(const Left(InvalidInputFailure())),
act: (bloc) =>
bloc.add(const GetConcreteNumberEvent(number: tNumberString)),
expect: () => [
LoadingState(),
ErrorState(message: const InvalidInputFailure().message)
],
);
So the complete answer is
You can try changing from:
expectLater(bloc!.state, emitsInOrder(expected));
To:
expectLater(bloc, emitsInOrder(expected));
In addition to changing 'bloc!.state' to 'bloc' (per QuangNV and ouflak), try also changing the 'async' in your test to the asynchronous generator, 'async*', to match to the code used in your Stream implementation.
test(
'should emit [Error] when the input is invalid',
() async* {
// arrange
You can try changing from:
expectLater(bloc!.state, emitsInOrder(expected));
To:
expectLater(bloc, emitsInOrder(expected));
Hope you can solve it!
I'm also following the same course & in addition of the ) async* { suggestion, I also needed to add quotation marks to have
yield Error(message: "INVALID_INPUT_FAILURE_MESSAGE");
In contrast,
expectLater(bloc.state,
expectLater(bloc!.state,
expectLater(bloc,
had not impact on passing the test successfully.
I've just started learning about #ngrx/store and #ngrx.effects and have created my first effect in my Angular/Ionic app. It runs ok the first time but if I dispatch the event to the store again (i.e when clicking the button again), nothing happens (no network call is made, nothing in console logs). Is there something obvious I'm doing wrong? Here's the effect:
#Effect() event_response$ = this.action$
.ofType(SEND_EVENT_RESPONSE_ACTION)
.map(toPayload)
.switchMap((payload) => this.myService.eventResponse(payload.eventId,payload.response))
.map(data => new SentEventResponseAction(data))
.catch((error) => Observable.of(new ErrorOccurredAction(error)));
Thanks
It sounds like an error is occurring. In that situation, the action in the observable returned by catch will be emitted into the effect's stream and the effect will then complete - which will prevent the effect from running after the error action is emitted.
Move the map and the catch into the switchMap:
#Effect() event_response$ = this.action$
.ofType(SEND_EVENT_RESPONSE_ACTION)
.map(toPayload)
.switchMap((payload) => this.myService
.eventResponse(payload.eventId, payload.response)
.map(data => new SentEventResponseAction(data))
.catch((error) => Observable.of(new ErrorOccurredAction(error)))
);
Composing the catch within the switchMap will prevent the effect from completing if an error occurs.
You must move map() and catchError() into swithchMap() as following
#Effect()
public event_response$ = this.action$.pipe(
ofType(SEND_EVENT_RESPONSE_ACTION),
switchMap((payload) => {
return this.myService.eventResponse(payload.eventId,payload.response).pipe(
map((data: DataType) => new SentEventResponseAction(data)),
catchError((error) => Observable.of(new ErrorOccurredAction(error)))
})
);
);
Please note that, evetResponse() method inside myService should return an observable in order to use pipe afterward.
In case your method inside service returns Promise, you can convert it into an observable by the use of from in the rxjs package as below:
import { from } from 'rxjs';
...
const promise = this.myService.eventResponse(payload.eventId,payload.response);
const observable = from(promise);
return observable.pipe(...
For more and detail description take a look at this link
I am using JustMock and NServiceBus.
I want to assert that following statement is executed once:
_bus.Publish<ISpecialEvent>(x =>
{
x.Prop1= "Very special";
});
so that's what I am using:
void Publish<T>(Action<T> messageConstructor);
Now I am mocking NServiceBus:
var serviceBus = Mock.Create<IBus>();
and assert:
Mock.Assert(() => serviceBus.Publish(Arg.IsAny<ISpecialEvent>()), Occurs.Once());
Well obviously this won't work as this does match the actual usage of .Publish
How do I do that?
it can be done like this:
Publish(Arg.IsAny>())
I guess I need some type of promise chain, but the syntax eludes me...
Within the same component:
I'm calling:
this.somethingService.getSomethings().then(somethings => this.somethings = somethings);
Then I need to call:
this.otherService.getOthers(this.somethings).then(others => this.others = others);
In the second service call I'm using the result of the first to perform aggregate functions on its content, but its empty when the second call is made, thus the second service returns empty.
How can I get the second service to wait until the first promise has been resolved.
Thanx
Steve
You can chain promises this way:
this.somethingService.getSomethings().then(somethings => {
this.somethings = somethings;
return this.otherService.getOthers(somethings);
}).then(others => {
this.others = others;
});
The second callback will receive the result of the promise returns by the first callback.