Flutter Stubbing : use Stub method's return value property - mockito

Hi this is the method i want to stub : the checkLimit method.
class MyClass {
final ResponseBase isAvailable =
await sampleRepository.checkLimit(data: _data);
if (isAvailable.status == ResponseStatus.notOk) {
yield NotAvailable(
ErrorType.limit,
data: _data,
errorResponse: isAvailable?.responseError,
);
return;
}
}
This is my Test
test('test when event is ScanQRCode checklimit not ok', () {
final List<ScanState> expectedStates = <CodeScanState>[
ScanReady(),
ScanAvailableFetching(),
ScanNotAvailable(
ScanErrorType.Limit,
redeemData: mockRedeemData,
),
];
when(mockPromosRepository.checkLimit(
redeemData: mockRedeemData))
.thenAnswer(
(_) => Future<ResponseBase>.value(mockResponseBase.status));
expectLater(scanBloc.state, emitsInAnyOrder(expectedStates));
scanBloc.dispatch(ScanQRCode(mockRedeemData));
});
what should be my return data to through the if condition ? thanks

Related

Flutter : GetX Variable initialise problem in Profile Data

I am using GetX statemangement on my flutter app. I want to fetch User's Profile data from server. That's Why I create a Profile Model Class and a Controller Screen. But I can't. Here is a problem to initialisation.
json Response -
{
"riderId": 1,
"riderName": "Ramiz Miah",
"riderContact": "01787656565",
"riderEmail": "ramiz#hotmail.com",
"riderImgRef": ""
}
Profile Model
class ProfileModel {
int? riderId;
String? riderName;
String? riderContact;
String? riderEmail;
String? riderImgRef;
ProfileModel(
{this.riderId,
this.riderName,
this.riderContact,
this.riderEmail,
this.riderImgRef});
ProfileModel.fromJson(Map<String, dynamic> json) {
riderId = json['riderId'];
riderName = json['riderName'];
riderContact = json['riderContact'];
riderEmail = json['riderEmail'];
riderImgRef = json['riderImgRef'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['riderId'] = riderId;
data['riderName'] = riderName;
data['riderContact'] = riderContact;
data['riderEmail'] = riderEmail;
data['riderImgRef'] = riderImgRef;
return data;
}
}
Controller
class ParofileController extends GetxController {
RxMap<String, dynamic> profileDetails = <String, dynamic>{}.obs;
//<============= Fetch and Assign DashBoard Today Details List
void fetchandAssignProfileDetails() async {
try {
ProfileApiService().getProfileDetails().then((resp) {
profileDetails.value = resp;
}, onError: (err) {
debugPrint(err.toString());
});
} catch (e) {
debugPrint(e.toString());
}
}
}
And API Service
class ProfileApiService extends GetConnect {
Future<ProfileModel?> getProfileDetails() async {
Uri url = Uri.parse("${AppConfig.baseUrl}/Rider/GetRiderDetails");
var response = await http.get(
url,
);
if (response.statusCode == 200) {
return ProfileModel.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to load User Profile');
}
}
}
And Now my Question is How to Define this variable here ( RxMap<String, dynamic> profileDetails = <String, dynamic>{}.obs; ), that's why it's work properly
I solved this
Rx<ProfileModel?> profile = ProfileModel().obs;
thanks.

nodejs function().anotherFunction() how they do it?

I install a library/module but I am curious how they do it
const modules = require('abc');
const app = new modules('123');
const client = app.f1('abcdef').f2('ghi');
console.log(client.to());
const client2 = app.f1('1111111').f2('2222');
console.log(client2.to());
console.log(client.to());
result is 123:abcdef-ghi
result is 123:1111111-2222
result is 123:abcdef-ghi
how they did it?
i want to create that example lib/module
please give me sample code
Depending on your exact requirements, something like this seems to work:
let state = Symbol("private")
class App {
constructor(arg) {
this[state] = arg
}
f1 = arg => new App(this[state] + ":" + arg)
f2 = arg => new App(this[state] + "-" + arg)
to = () => this[state]
}
Here each of the chainable method returns a new instance of the class, each keeping the temporary result as a local state. The to() method returns that state.
This is what I use for doing function().anotherFunction()
function func() {
console.log("ran func")
return {
"anotherFunc": function () {
console.log("ran another func")
}
}
}
func().anotherFunc()
You can also just return a object
const returnData = {
"anotherFunc": function () {
console.log("ran another func")
}
}
function func() {
console.log("ran func")
return returnData
}
func().anotherFunc()
Example of use:
function word1(in_1) {
return {
"word2": function (in_2) {
console.log(`Inputs: ${in_1} ${in_2}`)
}
}
}
word1("Hello").word2("World")
// Expected output: Inputs: Hello World

RedirectToAction inside a method doesn't work

Hello i have this method
private ActionResult CheckResult(ReactivationResponse result, GlobalObject globalInfo)
{
if (result == null)
{
return RedirectToAction("Failed", "Redirect", new { errorCode = 1014 });
}
else if (!result.IsReactivationSuccess && !result.IsOrderImported && !globalInfo.MemberInfo.IsWinbackAplicable)
{
return RedirectToAction("Failed", "Redirect", new { errorCode = 201 });
}
else if (!result.IsReactivationSuccess && result.Errors.Any())
{
if (result.Errors.Any(e => e.Message == "ApprovalPending"))
{
return View("Pending");
}
return RedirectToAction("Failed", "Redirect", new { errorCode = result.Errors.FirstOrDefault().StackTrace });
}
return null;
}
inside another Action Result
public ActionResult OtherMethod()
{
CheckResult(result, globalInfo);
//More code
return View()
}
I'm trying to redirect the code according to the result, and in case it doesn't apply, that the app continue and return the normal view.
But it doesn't work, if any of the if statements applies it doesn't redirect to anywhere, it continues with the normal viw.
I also tried to put a return before the method
return CheckResult(result, globalInfo);
and it works except if my method returns null, then it doesn't continue with the app.
I want to evaluate if it needs to redirect or if it should continue

How to define different context menus for different objects in autodesk forge

I want to define different context menus for different objects in forge viewer,this is my code
viewer.addEventListener(Autodesk.Viewing.AGGREGATE_SELECTION_CHANGED_EVENT,function(e){
if(viewer.getSelection().length==0){return;}
var selectId=viewer.getSelection()[0];
viewer.search("Cabinet",function(ids){
if(ids.indexOf(selectId)!=-1){
viewer.registerContextMenuCallback('CabinetMsg', function (menu, status) {
if (status.hasSelected) {
menu.push({
title: "CabinetMsg",
target: function () {
openLayer('CabinetMsg','954','775','CabinetMsg.html')
}
});
}
});
}else{
viewer.registerContextMenuCallback('CabinetMsg', function (menu, status) {
if (status.hasSelected) {
menu.forEach(function(el,index){
if(el.title=="CabinetMsg"){
menu.splice(menu.indexOf(index),1)
}
})
}
});
}
})
});
But push elements to the array is always later than the context menus show. My custom context menu is always show when I select another object. What I can do?
The codes you provided will create 2 new sub items to the context menu. Here is a way for this case, i.e. you have to write your own ViewerObjectContextMenu. In addition, you need do hitTest in ViewerObjectContextMenu.buildMenu to get dbId selected by the mouse right clicking. Here is the example for you:
class MyContextMenu extends Autodesk.Viewing.Extensions.ViewerObjectContextMenu {
constructor( viewer ) {
super( viewer );
}
isCabinet( dbId ) {
// Your logic for determining if selected element is cabinet or not.
return false;
}
buildMenu( event, status ) {
const menu = super.buildMenu( event, status );
const viewport = this.viewer.container.getBoundingClientRect();
const canvasX = event.clientX - viewport.left;
const canvasY = event.clientY - viewport.top;
const result = that.viewer.impl.hitTest(canvasX, canvasY, false);
if( !result || !result.dbId ) return menu;
if( status.hasSelected && this.isCabinet( result.dbId ) ) {
menu.push({
title: 'CabinetMsg',
target: function () {
openLayer( 'CabinetMsg', '954', '775', 'CabinetMsg.html' );
}
});
}
return menu;
}
}
After this, you could write an extension to replace default viewer context menu with your own menu. Here also is the example:
class MyContextMenuExtension extends Autodesk.Viewing.Extension {
constructor( viewer, options ) {
super( viewer, options );
}
load() {
this.viewer.setContextMenu( new MyContextMenu( this.viewer ) );
return true;
}
unload() {
this.viewer.setContextMenu( new Autodesk.Viewing.Extensions.ViewerObjectContextMenu( this.viewer ) );
return true;
}
}
Hope this help.

Zend\Stdlib\Exception\BadMethodCallException

Here the part of the stacktrace where I have a problem:
Zend\Stdlib\Exception\BadMethodCallException
File:
/var/www/html/zf2/vendor/zendframework/zendframework/library/Zend/Stdlib/Hydrator/ArraySerializable.php:28
Message:
Zend\Stdlib\Hydrator\ArraySerializable::extract expects the provided object to implement getArrayCopy()
Stack trace:
0 /var/www/html/zf2/vendor/zendframework/zendframework/library/Zend/Form/Fieldset.php(631): Zend\Stdlib\Hydrator\ArraySerializable->extract(Object(BookList\Model\Book))
1 /var/www/html/zf2/vendor/zendframework/zendframework/library/Zend/Form/Form.php(942): Zend\Form\Fieldset->extract()
2 /var/www/html/zf2/vendor/zendframework/zendframework/library/Zend/Form/Form.php(303): Zend\Form\Form->extract()
3 /var/www/html/zf2/module/BookList/src/BookList/Controller/BookController.php(59): Zend\Form\Form->bind(Object(BookList\Model\Book))
The action method in my Controller that call bind:
public function editAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
if (!$id) {
return $this->redirect()->toRoute('book');
}
try {
$book = $this->getBookTable()->getBook($id);
}
catch (\Exception $ex) {
return $this->redirect()->toRoute('book', array(
'action' => 'index'
));
}
$form = new BookForm();
$form->bind($book); // this is the line 59 of BookController
$form->get('submit')->setAttribute('value', 'Edit');
$request = $this->getRequest();
if ($request->isPost()) {
$form->setInputFilter($book->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$this->getBookTable()->saveBook($book);
// Redirect to list of books
return $this->redirect()->toRoute('book');
}
}
return array(
'id' => $id,
'form' => $form,
);
}
I checked also the BookTable class to see the object returned from the resulset and it's an istance of Book.
Than I opened the ArratSerializable.php and check the object passed and tre response is:
BookList\Model\Book Object ( [id] => 5 [author] => Gotye [title] => Making Mirrors [inputFilter:protected] => )
So it's a correct object, why doesn't it work?
How the result is returned you generally tell that to the ResultSet object while building your model. You actually set a prototype there for returning your result set saying, hey! "Use this prototype" which is, in your case, Book model. It does have a method called getArrayCopy() which is missing. That actually rises error in this case. So please add this to the Book model thus
class Book
{
// other properties and methods should be here
// add this method here
public function getArrayCopy()
{
return get_object_vars($this);
}
}

Resources