bloc handleError does not catch error in dart - unit-testing

So I am using the flutter_bloc plugin and I want to throw an exception for invalid states.
#injectable
class MyBloc extends Bloc<MyEvents, MyStates> {
MyBloc();
#override
MyStates get initialState => MyStates.initial();
#override
Stream<MyStates> mapEventToState(MyEvents event) async* {
throw Exception();
}
}
then I want to unit test whether the exception was thrown. I always get an unhandled error exception despite me using the handleError wrapper and the anything matcher. How to I catch this error?
expectLater(bloc.handleError((err, _) => print(err)), emits(anything));
The error message is
Unhandled error Exception occurred in bloc Instance of 'MyBloc'.

From Felix Angelov's answer here: https://github.com/felangel/bloc/issues/815
you can just let the exception bubble up by not wrapping the code in a
try/catch and then you can use blocTest with errors to verify an error
occurred.
blocTest(
'CounterBloc throws Exception when null is added',
build: () async => CounterBloc(),
act: (bloc) => bloc.add(null),
errors: [
isA<Exception>(),
]
);
Hope that helps 👍
Thank you so much :) it is exactly what I was looking for :)

Related

how to catch an exception inside a scala future' s callback onCompelete Success case?

I have a future and sending that value to the caller actor my problem is I am calling future.onCompelete and inside its case Success callback I am getting an exception I want to know what is the right way to catch that exception as the Failure block will not work in this use case
here is my code
val future = Futute{calling a http route which sends back a response}
future.onComplete {
case Success (response) => //do some processing with response got some exception while doing this
throw new RunTimeException("got exception while working the response")
sender() ! response
case Failure (ex) => ex.printStackTrace
}
in the above code, I am unable to catch the exception I only got AskTimeOutException when i am calling this future code
I can only catch the exception if I surround it with try-catch
like this
val future = Futute{calling a http route which sends back a response}
future.onComplete {
case Success (response) => //do some processing with response got some exception while doing this
try {
throw new RunTimeException("got exception while working the response")
sender() ! response
}
catch {
case ex:Exception(e)=>log.error("got an exception",ex)
}
case Failure (ex) => ex.printStackTrace
}
is this the right approach to do this? or is there any better way to do this?
In general, onComplete shouldn't be used if you care about an exception thrown in the callback (nor should the other Unit-returning method which needs an (implicit) ExecutionContext: foreach).
The most general approach and the most similar to onComplete is to use transform (or its cousin transformWith: transform is to transformWith as map is to flatMap), for example
future.transform {
case Success(response) =>
// these are both equivalent... the exception will get wrapped into a failed future
Failure(new RuntimeException("BOOM!"))
throw new RuntimeException("BOOM!")
case f # Failure(ex) =>
ex.printStackTrace()
f // pass-through
}

How to assert the content of a service message exception in a Grails unit test

I am using Grails 4.0.3 and want to assert that an exception is thrown in a given situation. Below, my PidService.
def validatePidIssuingConclusionDocument(JSONObject pidIssuingConclusionDocument){
String message = "Document issuing number is mandatory"
if(!pidIssuingConclusionDocument.has("docIssuingNumber")){throw new Exception(message)}
}
Below, my test case:
void "wrong document"() throws Exception {
JSONObject documentWithoutIssuingNumber = new JSONObject()
documentWithoutIssuingNumber.accumulate("docIssuingNumber","123")
pidService.buildPidIssuingOrder(documentWithoutIssuingNumber)
// How can I assert that the exception is thrown and verify it message.
}
I tried to use try/catch in the test case without success. Could anyone help me? I need to assert that the exception is thrown and the message is Document issuing number is mandatory in the given case.
I need to assert that the exception is thrown and the message is
Document issuing number is mandatory in the given case.
I can't provide an executable example around the code you provided because some things are missing (like buildPidIssuingOrder). See the project at https://github.com/jeffbrown/dnunesexception which contains an example that shows a way to deal with the exception in a test though.
grails-app/services/dnunesexception/PidService.groovy
package dnunesexception
import org.grails.web.json.JSONObject
class PidService {
def buildPidIssuingOrder(JSONObject pidIssuingConclusionDocument) {
throw new Exception('Document issuing number is mandatory')
}
}
src/test/groovy/dnunesexception/PidServiceSpec.groovy
package dnunesexception
import grails.testing.services.ServiceUnitTest
import spock.lang.Specification
import org.grails.web.json.JSONObject
class PidServiceSpec extends Specification implements ServiceUnitTest<PidService>{
void "test something"() {
when:
JSONObject documentWithoutIssuingNumber = new JSONObject()
documentWithoutIssuingNumber.accumulate("docIssuingNumber","123")
service.buildPidIssuingOrder(documentWithoutIssuingNumber)
then:
def e = thrown(Exception)
and:
e.message == 'Document issuing number is mandatory'
}
}

How to get get page source in codeception yii 2

I need save the source code of failed test to fix it. How to get the source html while using codeception test in yii 2?
I cannot get $I->grabPageSource() and $I->_getResponseContent() to work though there are these exact functions.
public function checkCall(FunctionalTester $I)
{
$I->amOnRoute('mx/ed',['model' => 'State']);
$I->seeResponseCodeIs(200);
$I->seeResponseCodeIsSuccessful();
$html = $I->grabPageSource();
}
Codeception saves page source of last request for all failed tests in tests/_output directory by itself, there is nothing for you to do.
Failed assertion throws exception so your code after $I->seeResponseCodeIsSuccessful is not executed.
If you want to implement some custom error handling in specific test, you can wrap assertions in try-catch block and grabPageSource inside catch.
public function checkCall(FunctionalTester $I)
{
$I->amOnRoute('mx/ed',['model' => 'State']);
try{
$I->seeResponseCodeIs(200);
$I->seeResponseCodeIsSuccessful();
} catch (Exception $e) {
$html = $I->grabPageSource();
//do your error handling here
throw $e; //rethrow exception to make test fail
}
}
If you want to implement custom error handling for all tests, add _failed method to Helper\Functional class in tests/_support/Helper directory.
public function _failed(\Codeception\TestInterface $test, $fail)
{
$testName = $test->getMetadata()->getName();
$pageSource = $this->getModule('Yii2')->getPageSource();
//do your error handling here
}

how test that the connection works in Doctrine 2?

I'm looking for a way to test if a connection is working or not with Doctrine 2.
As in my application users can change by themselves the information connections, I want to check if the user has entered the right login and password.
How can I do that?
I tried to put this code into a try/catch block :
try{
$entityManager = $this->getEntityManager() ;
$repository = $entityManager->getRepository('Authentification\Entity\User');
$userToIdentify = $repository->findOneBy(array('login' => $this->_username, 'password' => $this->_password));
}catch(Exception $e){
$code = Result::FAILURE ;
$identity = "unknow" ;
$messages = array(
"message" => "Wrong login/password combination",
) ;
}
The problem is that even if the information connection is correct, I cannot catch the exception.
Otherwise I get the following error :
<b>Fatal error</b>: Uncaught exception 'Zend\View\Exception\RuntimeException'
with message 'Zend\View\Renderer\PhpRenderer::render: Unable to render template
"layout/layout"; resolver could not resolve to a file' in C:\xampp\htdocs\poemsV3\vendor\zendframework\zendframework\library\Zend\View\Renderer\PhpRenderer.php:451 Stack trace: #0 C:\xampp\htdocs\poemsV3\vendor\zendframework\zendframework\library\Zend\View\View.php(203): Zend\View\Renderer\PhpRenderer->render(Object(Zend\View\Model\ViewModel)) #1 C:\xampp\htdocs\poemsV3\vendor\zendframework\zendframework\library\Zend\Mvc\View\Http\DefaultRenderingStrategy.php(128): Zend\View\View->render(Object(Zend\View\Model\ViewModel)) #2 [internal function]: Zend\Mvc\View\Http\DefaultRenderingStrategy->render(Object(Zend\Mvc\MvcEvent))#3 C:\xampp\htdocs\poemsV3\vendor\zendframework\zendframework\library\Zend\EventManager\EventManager.php(469): call_user_func(Array, Object(Zend\Mvc\MvcEvent))#4 C:\xampp\htdocs\poemsV3\vendor\zendframework\zendframework\library\Zend\EventManager\EventMa in <b>C:\xampp\htdocs\poemsV3\vendor\zendframework\zendframework\library\Zend\View\Renderer\PhpRenderer.php</b> on line <b>451</b><br />
Do you have any idea in how I could test if the connection works?
Thank you.
Do not use the EntityManager directly. You can instead use following to check the connection parameters:
try {
$entityManager->getConnection()->connect();
} catch (\Exception $e) {
// failed to connect
}
That's sadly the only real way to check if something went wrong, since the exception type changes depending on the driver you use.
For the other exception (the view-related one) you simply have to adjust your view scripts path. I suggest you to keep the skeleton application module enabled so that the default layout is always there: you can override it at any time.
You can use.
$cnx = $this->getDoctrine()->getConnection();
$cnx->isConnected() ?
'Connected' :
'not connected';

Axis2 : Handling Userdefined Exceptions

I am seeing Exception handling in Apache Axis2 Webservices .
My Skelton class throws a Userdefined Exception named as "NoUserFound" , which in have configured inside WSDL file
Inside my skelton class
public samples.quickstart.xsd.GetPriceResponse getPrice(
samples.quickstart.xsd.GetPrice getPrice0)
throws GetSolutionByIdFault {
samples.quickstart.xsd.GetPriceResponse response = new samples.quickstart.xsd.GetPriceResponse();
response.set_return("Hi");
String value = (String) getPrice0.getSymbol();
if (value.equals("Pavan"))
throw new GetSolutionByIdFault("name not present");
return response;
}
Inside my client class , i am handling this in this way :
try {
// Some Logic here
}
catch (AxisFault er) {
er.getMessage();
}
catch (Exception e) {
e.printStackTrace();
}
So when ever a user defined exception is thrown for example (GetSolutionByIdFault) , i am handling it in the AxisFault block .
is this the correct approach ??
Yes, that looks fine - if you want, you catch more specific exceptions as well...
It depends on what you have to do in order to handle the exception. If you need to do special things according to the backend exception then you need to catch each and every exception and handle them separately.
Normally I used to handle exceptions separately.