expectException doesn't detect the exception - yii2

I am trying to test database records retrieving. My test looks like:
use yii\db\Exception;
class UserTest extends Unit
{
protected $tester;
private $_user;
public function _before()
{
$this->_user = new User();
}
public function testRetrievingFALSE()
{
$this->expectException(Exception::class, function(){
$this->_user->retrieveRecords();
});
}
}
I saw the expectException() method in the documentation. My model method looks like this:
public function retrieveRecords()
{
$out = ArrayHelper::map(User::find()->all(), 'id', 'username');
if($out)
return $out;
else
throw new Exception('No records', 'Still no records in db');
}
What am I doing wrong in this scenario?
In terminal:
Frontend\tests.unit Tests (1) ------------------------------------------------------------------------------------------
x UserTest: Retrieving false (0.02s)
------------------------------------------------------------------------------------------------------------------------
Time: 532 ms, Memory: 10.00MB
There was 1 failure:
---------
1) UserTest: Retrieving false
Test tests\unit\models\UserTest.php:testRetrievingFALSE
Failed asserting that exception of type "yii\db\Exception" is thrown.
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

You're not using the same method which you're referring to. You should use it on actor instance, not on unit test class itself. So either:
$this->tester->expectException(Exception::class, function(){
$this->_user->retrieveRecords();
});
Or in acceptance tests:
public function testRetrievingFALSE(AcceptanceTester $I) {
$I->expectException(Exception::class, function(){
$this->_user->retrieveRecords();
});
}
If you call it on $this in test class, method from PHPUnit will be used, which works differently:
public function testRetrievingFALSE() {
$this->expectException(Exception::class);
$this->_user->retrieveRecords();
}
See more examples in PHPUnit documentation.

Related

Spring WebFlux; unit testing exception thrown in Mono.map()

I have some code that returns Mono<List<UserObject>>. The first thing I want to do is check the List is not empty, and if it is, throw a NoUsersFoundException. My code looks like this:
IUserDao.java
Mono<List<UserAccount>> getUserProfiles(final Set<UserQueryFilter> filters,
final Set<String> attributes);
GetUserAccount.java
public Mono<UserAccount> doGetUserAccount() {
return userDao.getUserProfiles(filters, attributes)
.map(list -> {
if (CollectionUtils.isEmpty(list)) {
throw new NoUsersFoundException();
}
return list;
})
.map(this::removePermissions)
.map(this::removeDuplicates);
}
I want to write a unit test that will test that the NoUsersFoundException is thrown when userDao.getUserProfiles(filters, attributes) returns an empty list. When I use Mockito#when with a .thenReturn(), the test will, as expected, return immediately once userDao.getUserProfiles(...) is called without continuing the flow into the .map() where the list is checked and exception thrown.
#Mock
private IUserDao userDao;
private UserPolicies userPolicies;
#BeforeEach
public void init() {
userPolicies = new UserPolicies(Set.of("XYZ", USER_AFF, "123"),
Set.of(TestUserConstants.ID, TestUserConstants.SUBSCRIPTION_LEVEL));
}
#Test
void shouldThrowExceptionIfNoUsersFound() {
final Set<UserFilter> filters = new UserFilterBuilder().withId(ID)
.withSubscription(PREMIUM)
.build();
when(userDao.getUserProfiles(filters, userPolicies.getUserAttributeIds()))
.thenReturn(Mono.just(Collections.emptyList()));
testClass = new GetUserAccount(userDao,
userPolicies,
filters,
userPolicies.getUserAttributeIds());
assertThatThrownBy(() -> testClass.doGetUserAccount()).isInstanceOf(NoUsersFoundException.class);
}
I have tried .thenAnswer() but it essentially does the same thing as the method called is not a void:
userDao.getUserProfiles(filters, userPolicies.getUserAttributeIds()))
.thenAnswer((Answer<Mono<List>>) invocationOnMock -> Mono.just(Collections.emptyList()));
I can't see how using reactor.test.StepVerifier would work for this case.
i dont really understand what you are asking for, but we commonly dont "throw" exceptions in reactor. We return a Mono#error downstream, and different operators will react accordingly as the error travels downstream.
public Mono<List<Foobar> fooBar(filters, attributes) {
return daoObject.getUserProfiles(filters, attributes)
.map(list -> {
if (CollectionUtils.isEmpty(list)) {
// Return a mono#error
return Mono.error( ... );
}
return list;
})
}
And then test using the step verifier. With either expectNext or expectError.
// Happy case
StepVerifier.create(
fooBar(filters, attributes))
.expectNext( ... )
.verify();
// Sad case
StepVerifier.create(
fooBar(filters, attributes))
.expectError( ... )
.verify();

Conditionally skip a Junit 5 test

In my Junit Jupiter API 5.5 test, I am calling my method which internally makes a HTTP call to a remote service.
Now the remote service can be down or behave incorrectly. I want to skip my test in case the remote service is not behaving expectedly.
#Test
void testMe() {
// do something
Result res1 = myObject.retrieveResults(params)
// assert something
Result res2 = myObject.retrieveResults(param2)
//asert on results
}
Result retrieveResults(Parameters param) {
// do something
// call to remote service
// if they do not give result throw CustomException()
// return Result
}
So basically in my test i would want to check if myObject.retrieveResult is throwing CustomException then skip that test, otherwise evaluate normally.
We have 2 different ways to accomplish this tasks in JUnit 5.
For demo purposes, I have created a basic class which sends a request to the url
that is passed as an argument to its call(String url) method and
returns true or false depending on the request result.
The body of the method is irrelevant here.
Using Assumptions.assumeTrue()/assumeFalse() methods
Assumptions class provides us with two overloaded methods - assumeTrue
and assumeFalse. The idea is that, if the assumption is wrong, the test will be skipped.
So, the test will be something like this.
#Test
void call1() {
Assumptions.assumeTrue(new EndpointChecker(), "Endpoint is not available");
Assertions.assertTrue(HttpCaller.call("https://www.google.com"));
}
Here is the code for EndpointChecker class.
static class EndpointChecker implements BooleanSupplier {
#Override
public boolean getAsBoolean() {
// check the endpoint here and return either true or false
return false;
}
}
When the test is run, the availability of the endpoint will be checked first, if it is up, then the test will run.
Using JUnit 5 extension mechanisms.
So, let's start with creating the annotation. It is pretty straightforward.
#Retention(RetentionPolicy.RUNTIME)
#ExtendWith(EndpointAvailabilityCondition.class)
public #interface SkipWhenEndpointUnavailable {
String uri();
}
And EndpointAvailabilityCondition class. Even though, it looks big, overall logic is very simple.
import static org.junit.platform.commons.util.AnnotationUtils.findAnnotation;
public class EndpointAvailabilityCondition implements ExecutionCondition {
#Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
final var optional = findAnnotation(context.getElement(), SkipWhenEndpointUnavailable.class);
if (optional.isPresent()) {
final SkipWhenEndpointUnavailable annotation = optional.get();
final String uri = annotation.uri();
// check connection here start
boolean result = false; // dummy value
// check connection here end
if (result) {
return ConditionEvaluationResult.enabled("Connection is up");
} else {
return ConditionEvaluationResult.disabled("Connection is down");
}
}
return ConditionEvaluationResult.enabled("No assumptions, moving on...");
}
}
Hence, we can do the following in our tests.
#Test
#SkipWhenEndpointUnavailable(uri = "https://www.google.com")
void call2() {
Assertions.assertTrue(HttpCaller.call("https://www.google.com"));
}
We can go ahead and add #Test annotation over #SkipWhenEndpointUnavailable and remove it from our test code. Like, so:
#Retention(RetentionPolicy.RUNTIME)
#ExtendWith(EndpointAvailabilityCondition.class)
#Test
public #interface SkipWhenEndpointUnavailable {
String uri();
}
class HttpCallerTest {
#SkipWhenEndpointUnavailable(uri = "https://www.google.com")
void call2() {
Assertions.assertTrue(HttpCaller.call("https://www.google.com"));
}
}
I hope it helps.

How do I write a unit-test to throw an exception from the Mock method of Operation return type?

I would like to write a unit-test to throw an exception from the Mock method of Operation return type.
I'm writing the unit-test with Spock in Groovy.
There are class A, and B
// class A
private ClassB b;
Promise<String> foo() {
return b.methodX()
.nextOp(s -> {
return b.methodY();
});
}
Return type of methodP() is Promise<>
Return type of methodO() is Operation
// class B
public Promise<String> methodP() {
return Promise.value("abc");
}
public Operation methodO() {
return Operation.noop();
}
Unit-test for foo() method of Class A
Mocking ClassB in the unit-test
// Spock unit-test
ClassA a = new ClassA()
ClassB b = Mock()
def 'unit test'() {
given:
when:
execHarness.yield {
a.foo()
}.valueOrThrow
then:
1 * b.methodP() >> Promise.value("some-string")
1 * b.methodO() >> new Exception("my-exception")
Exception e = thrown(Exception)
e.getMessage() == "my-exception"
}
I expected the Exception is thrown, but GroovyCaseException was thrown and test failed.
Error message says,
org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'java.lang.Exception: my-exception' with class 'java.lang.Exception' to class 'ratpack.exec.Operation'
Change this line:
1 * b.methodO() >> new Exception("my-exception")
on:
1 * b.methodO() >> { throw new Exception("my-exception") }
Because methodO() is not expected to return Exception instance (as in your example) but it is expected to be thrown (by using closure).

phpunit expectException() wrong exception name

When I run PHPUnit 6.5.13. and have a test method following this example PHPUnit Testing Exceptions Documentation
public function testSetRowNumberException()
{
$this->expectException(\InvalidArgumentException::class);
$result = $this->tableCell->setRowNumber('text');
}
that tests this method:
public function setRowNumber(int $number) : TableCell
{
if (!is_int($number)) {
throw new \InvalidArgumentException('Input must be an int.');
}
$this->rowNumber = $number;
return $this;
}
I got this failure:
Failed asserting that exception of type "TypeError" matches expected exception "InvalidArgumentException".
the question is why "TypeError" is taken to assertion and how to make assertion use InvalidArgumentException?
Got it. The thing is I used typing set to int that's why the code didn't even reach the thow command.
it works if tested method is without set typing to int:
public function setRowNumber($number) : TableCell
{
if (!is_int($number)) {
throw new \InvalidArgumentException('Input must be an int.');
}
$this->rowNumber = $number;
return $this;
}
or when the test has TypeError
public function testSetRowNumberException()
{
$this->expectException(\TypeError::class);
$result = $this->tableCell->setRowNumber('text');
}
I'll stay with the second example.

Yii2 before Validate throw PHP Warning

I used beforeValidate($insert) function and it thrown a PHP Warning when I access my post listing page:
http://localhost/yiiapp/backend/web/index.php?r=post/index
PHP Warning – yii\base\ErrorException
Missing argument 1 for app\models\Post::beforeValidate(), called in /var/www/html/yiiapp/vendor/yiisoft/yii2/base/Model.php on line 341 and defined
but when I access my create page, this Exception gone away:
http://localhost/yiiapp/backend/web/index.php?r=post/create
Actually I want to assign value one of my attribute user_id before validation in Post Model.
Here is Post Model:
class Post extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'post';
}
public function beforeValidate($insert)
{
if (parent::beforeValidate($insert)) {
$this->user_id = Yii::$app->user->id;
return true;
}
return false;
}
---
}
Why this Exception?
How I can solve this issue?
According to doc http://www.yiiframework.com/doc-2.0/yii-base-model.html#beforeValidate()-detail method beforeValidate has no attributes. Use it this way:
public function beforeValidate()
{
if (parent::beforeValidate()) {
return true;
}
return false;
}