Best junit code snippet using org.junit.Assume.assumeNotNull
Source:OneDriveTest.java
...18import static org.junit.Assert.assertNotNull;19import static org.junit.Assert.assertNull;20import static org.junit.Assert.assertTrue;21import static org.junit.Assert.fail;22import static org.junit.Assume.assumeNotNull;2324import java.io.File;25import java.io.FileNotFoundException;26import java.io.IOException;27import java.net.URL;28import java.util.Map;2930import org.junit.Before;31import org.junit.Ignore;32import org.junit.Test;3334import com.mxhero.plugin.cloudstorage.onedrive.api.Items.ConflictBehavior;35import com.mxhero.plugin.cloudstorage.onedrive.api.command.ApiException;36import com.mxhero.plugin.cloudstorage.onedrive.api.model.Drive;37import com.mxhero.plugin.cloudstorage.onedrive.api.model.Item;38import com.mxhero.plugin.cloudstorage.onedrive.api.model.ItemList;39import com.mxhero.plugin.cloudstorage.onedrive.api.model.ItemReference;40import com.mxhero.plugin.cloudstorage.onedrive.api.model.Permission;41import com.mxhero.plugin.cloudstorage.onedrive.api.model.ThumbnailSetList;4243public class OneDriveTest {44 45 private TestEnviroment testEnviroment;46 47 @Before48 public void beforeClass() throws IOException{49 if(testEnviroment==null){50 try{51 testEnviroment=OneDrive.JACKSON.readValue(new URL(System.getProperty("test.enviroment.json.url")), TestEnviroment.class);52 }catch(Exception e){53 System.out.println(" couldnt read TestEnviroment fro url in SystemProperty test.enviroment.json.url with value "+System.getProperty("test.enviroment.json.url"));54 e.printStackTrace();55 }56 }57 }58 59 private File getFile(){60 return new File(Thread.currentThread().getContextClassLoader().getResource("logo_96x96.png").getFile());61 }62 63 private OneDrive createApi(){64 return new OneDrive.Builder()65 .credential(testEnviroment.getCredential())66 .application(testEnviroment.getApplication())67 .build();68 }69 70 @Ignore71 @Test72 public void emails() {73 assumeNotNull(testEnviroment);7475 Map<String, Object> response = OneDrive.emails(testEnviroment.getCredential().getAccessToken());76 assertNotNull(response);77 System.out.println(response.toString());78 }79 80 @Test81 public void testDriveUserDefault(){82 assumeNotNull(testEnviroment);8384 Drive drive = createApi().drives().userDefault();85 assertNotNull(drive);86 System.out.println(drive.toString());87 }88 89 @Test90 public void testDriveById(){91 assumeNotNull(testEnviroment);9293 Drive drive = createApi().drives().get("bf667a0c62207823");94 assertNotNull(drive);95 System.out.println(drive.toString());96 }97 98 @Test99 public void listRootChildrens(){100 assumeNotNull(testEnviroment);101102 ItemList itemList = createApi().items().childrenByPath("");103 assertNotNull(itemList);104 System.out.println(itemList.toString());105 }106 107 @Test108 public void listChildrenByPath(){109 assumeNotNull(testEnviroment);110111 ItemList itemList = createApi().items().childrenByPath("Documents");112 assertNotNull(itemList);113 assertTrue(itemList.getValue().size()>0);114 System.out.println(itemList.toString());115 }116 117 @Test118 public void getItemById(){119 assumeNotNull(testEnviroment);120 Item item =createApi().items().metadataById("BF667A0C62207823!1912");121 assertNotNull(item);122 System.out.println(item.toString());123 }124 125 @Test126 public void getItemByIdWithParameters(){127 assumeNotNull(testEnviroment);128129 Items items = createApi().items();130 Item item =items.metadataById("BF667A0C62207823!1912", new Parameters().select("id,name"));131 assertNotNull(item.getName());132 assertNull(item.getcTag());133 System.out.println(item.toString()); 134 item=items.metadataById("BF667A0C62207823!1912", new Parameters().expand("children(select=id,name)").select("id,name,children"));135 assertNotNull(item.getChildren());136 System.out.println(item.toString()); 137 }138139 @Test140 public void getItemByPath(){141 assumeNotNull(testEnviroment);142143 Items items = createApi().items();144 Item item = items.metadataByPath("demo");145 assertNotNull(item);146 System.out.println(item.toString());147 item = items.metadataByPath("demo/saveAndShare");148 assertNotNull(item);149 System.out.println(item.toString());150 }151152 @Test153 public void searchByPath(){154 assumeNotNull(testEnviroment);155156 ItemList searchResult = createApi().items().searchByPath("Pictures", new Parameters().query("uploadtest.png")); 157 assertTrue(searchResult.getApproximateCount()>0);158 assertTrue(searchResult.getValue().size()>0);159 System.out.println(searchResult);160 }161 162 @Test163 public void thumbnails(){164 assumeNotNull(testEnviroment);165166 ThumbnailSetList list = createApi().items().thumbnails("BF667A0C62207823!104", null); 167 System.out.println(list);168 assertTrue(list.getValue().size()>0);169 }170 171 @Test172 public void simpleUpload(){173 assumeNotNull(testEnviroment);174175 Items items = createApi().items();176 items.simpleUploadByPath("Pictures"177 , "[uploadtest] and ().png"178 , getFile()179 , ConflictBehavior.replace);180 items.simpleUploadById(items.metadataByPath("Pictures").getId()181 , "[uploadtest].png"182 , getFile()183 , ConflictBehavior.replace);184 }185 186 @Test187 public void delete() throws FileNotFoundException{188 assumeNotNull(testEnviroment);189 Items items = createApi().items();190 items.simpleUploadByPath("Pictures"191 , "delete.png"192 , getFile()193 , ConflictBehavior.replace);194 items.deleteByPath("Pictures/delete.png");195 assertNull(items.metadataByPath("Pictures/delete.png"));196 }197 198 @Test199 public void apiException() throws FileNotFoundException{200 assumeNotNull(testEnviroment);201 Items items = createApi().items();202 items.deleteByPath("Pictures/delete.png");203 items.simpleUploadByPath("Pictures"204 , "delete.png"205 , getFile()206 , ConflictBehavior.replace);207 try{208 items.simpleUploadByPath("Pictures"209 , "delete.png"210 , getFile()211 , ConflictBehavior.fail);212 fail();213 }catch(ApiException e){214 assertNotNull(e.getReasonPhrase());215 assertNotNull(e.getStatusCode());216 assertNotNull(e.getError());217 System.out.println("error found "+e.getError().toString());218 }219 }220 221 @Test222 public void copy(){223 assumeNotNull(testEnviroment);224225 Items items = createApi().items();226 items.deleteByPath("Pictures/copy_1.png");227 items.deleteByPath("Pictures/copy.png");228 Item parent = items.metadataByPath("Pictures");229 Item copyItem = items.simpleUploadByPath("Pictures"230 , "copy.png"231 , getFile()232 , ConflictBehavior.replace);233 items.copyById(copyItem.getId(), 234 new ItemReference.Builder().id(parent.getId()).build()235 , "copy_1.png");236 long timestamp = System.currentTimeMillis();237 while(items.metadataByPath("Pictures/copy_1.png")== null && (timestamp+5000)<System.currentTimeMillis()){238 try {239 Thread.sleep(500);240 } catch (InterruptedException e) {241 }242 }243 items.deleteByPath("Pictures/copy_1.png");244 items.deleteByPath("Pictures/copy.png");245 }246 247 @Test248 public void move(){249 assumeNotNull(testEnviroment);250251 Items items = createApi().items();252 items.deleteByPath("Documents/move.png");253 items.deleteByPath("Pictures/move.png");254 Item parent = items.metadataByPath("Documents");255 Item moveItem = items.simpleUploadByPath("Pictures"256 , "move.png"257 , getFile()258 , ConflictBehavior.replace);259 items.moveById(moveItem.getId(), 260 new ItemReference.Builder().id(parent.getId()).build());261 long timestamp = System.currentTimeMillis();262 while(items.metadataByPath("Documents/move.png")== null && (timestamp+5000)<System.currentTimeMillis()){263 try {264 Thread.sleep(500);265 } catch (InterruptedException e) {266 }267 }268 items.deleteByPath("Documents/move.png");269 items.deleteByPath("Pictures/move.png");270 }271 272 @Test273 public void createFolder(){274 assumeNotNull(testEnviroment);275276 Items items = createApi().items();277 System.out.println(items.deleteByPath("folder"));278 System.out.println(items.createFolder("root", "folder.", ConflictBehavior.rename).getId());279 System.out.println(items.createFolder(items.metadataByPath("folder").getId(), "subfolder", ConflictBehavior.fail));280 System.out.println(items.deleteByPath("folder"));281 items.createFolder("root", "marcelo@gmail.com", ConflictBehavior.rename);282 }283 284 @Test285 public void createLink(){286 assumeNotNull(testEnviroment);287288 Items items = createApi().items();289 items.deleteByPath("Pictures/link.png");290 Item item = items.simpleUploadByPath("Pictures"291 , "link.png"292 , getFile()293 , ConflictBehavior.replace);294 Permission permission = items.createLinkById(item.getId(), "view");295 System.out.println(permission);296 }297 298}
...
Source:ManagedIdentityCredentialLiveTest.java
...24 private static final String PROPERTY_IDENTITY_ENDPOINT = "IDENTITY_ENDPOINT";25 private static final String PROPERTY_IDENTITY_HEADER = "IDENTITY_HEADER";26 @Test27 public void testMSIEndpointWithSystemAssigned() throws Exception {28 org.junit.Assume.assumeNotNull(CONFIGURATION.get(Configuration.PROPERTY_MSI_ENDPOINT));29 org.junit.Assume.assumeTrue(CONFIGURATION.get(Configuration.PROPERTY_AZURE_CLIENT_ID) == null);30 org.junit.Assume.assumeNotNull(CONFIGURATION.get(AZURE_VAULT_URL));31 IdentityClient client = new IdentityClientBuilder().build();32 StepVerifier.create(client.authenticateToManagedIdentityEndpoint(33 CONFIGURATION.get(PROPERTY_IDENTITY_ENDPOINT),34 CONFIGURATION.get(PROPERTY_IDENTITY_HEADER),35 CONFIGURATION.get(Configuration.PROPERTY_MSI_ENDPOINT),36 CONFIGURATION.get(Configuration.PROPERTY_MSI_SECRET),37 new TokenRequestContext().addScopes("https://management.azure.com/.default")))38 .expectNextMatches(accessToken -> accessToken != null && accessToken.getToken() != null)39 .verifyComplete();40 }41 @Test42 public void testMSIEndpointWithSystemAssignedAccessKeyVault() throws Exception {43 org.junit.Assume.assumeNotNull(CONFIGURATION.get(Configuration.PROPERTY_MSI_ENDPOINT));44 org.junit.Assume.assumeTrue(CONFIGURATION.get(Configuration.PROPERTY_AZURE_CLIENT_ID) == null);45 org.junit.Assume.assumeNotNull(CONFIGURATION.get(AZURE_VAULT_URL));46 ManagedIdentityCredential credential = new ManagedIdentityCredentialBuilder().build();47 SecretClient client = new SecretClientBuilder()48 .credential(credential)49 .vaultUrl(CONFIGURATION.get(AZURE_VAULT_URL))50 .buildClient();51 KeyVaultSecret secret = client.getSecret(VAULT_SECRET_NAME);52 Assert.assertNotNull(secret);53 Assert.assertEquals(VAULT_SECRET_NAME, secret.getName());54 Assert.assertNotNull(secret.getValue());55 }56 @Test57 public void testMSIEndpointWithUserAssigned() throws Exception {58 org.junit.Assume.assumeNotNull(CONFIGURATION.get(Configuration.PROPERTY_MSI_ENDPOINT));59 org.junit.Assume.assumeNotNull(CONFIGURATION.get(Configuration.PROPERTY_AZURE_CLIENT_ID));60 org.junit.Assume.assumeNotNull(CONFIGURATION.get(AZURE_VAULT_URL));61 IdentityClient client = new IdentityClientBuilder()62 .clientId(CONFIGURATION.get(Configuration.PROPERTY_AZURE_CLIENT_ID))63 .build();64 StepVerifier.create(client.authenticateToManagedIdentityEndpoint(65 CONFIGURATION.get(PROPERTY_IDENTITY_ENDPOINT),66 CONFIGURATION.get(PROPERTY_IDENTITY_HEADER),67 CONFIGURATION.get(Configuration.PROPERTY_MSI_ENDPOINT),68 CONFIGURATION.get(Configuration.PROPERTY_MSI_SECRET),69 new TokenRequestContext().addScopes("https://management.azure.com/.default")))70 .expectNextMatches(accessToken -> accessToken != null && accessToken.getToken() != null)71 .verifyComplete();72 }73 @Test74 public void testMSIEndpointWithUserAssignedAccessKeyVault() throws Exception {75 org.junit.Assume.assumeNotNull(CONFIGURATION.get(Configuration.PROPERTY_MSI_ENDPOINT));76 org.junit.Assume.assumeNotNull(CONFIGURATION.get(Configuration.PROPERTY_AZURE_CLIENT_ID));77 org.junit.Assume.assumeNotNull(CONFIGURATION.get(AZURE_VAULT_URL));78 ManagedIdentityCredential credential = new ManagedIdentityCredentialBuilder()79 .clientId(CONFIGURATION.get(Configuration.PROPERTY_AZURE_CLIENT_ID))80 .build();81 SecretClient client = new SecretClientBuilder()82 .credential(credential)83 .vaultUrl(CONFIGURATION.get(AZURE_VAULT_URL))84 .buildClient();85 KeyVaultSecret secret = client.getSecret(VAULT_SECRET_NAME);86 Assert.assertNotNull(secret);87 Assert.assertEquals(VAULT_SECRET_NAME, secret.getName());88 Assert.assertNotNull(secret.getValue());89 }90 @Test91 public void testIMDSEndpointWithSystemAssigned() throws Exception {92 org.junit.Assume.assumeTrue(checkIMDSAvailable());93 org.junit.Assume.assumeTrue(CONFIGURATION.get(Configuration.PROPERTY_AZURE_CLIENT_ID) == null);94 org.junit.Assume.assumeNotNull(CONFIGURATION.get(AZURE_VAULT_URL));95 IdentityClient client = new IdentityClientBuilder().build();96 StepVerifier.create(client.authenticateToIMDSEndpoint(97 new TokenRequestContext().addScopes("https://management.azure.com/.default")))98 .expectNextMatches(accessToken -> accessToken != null && accessToken.getToken() != null)99 .verifyComplete();100 }101 @Test102 public void testIMDSEndpointWithSystemAssignedAccessKeyVault() throws Exception {103 org.junit.Assume.assumeTrue(checkIMDSAvailable());104 org.junit.Assume.assumeTrue(CONFIGURATION.get(Configuration.PROPERTY_AZURE_CLIENT_ID) == null);105 org.junit.Assume.assumeNotNull(CONFIGURATION.get(AZURE_VAULT_URL));106 ManagedIdentityCredential credential = new ManagedIdentityCredentialBuilder().build();107 SecretClient client = new SecretClientBuilder()108 .credential(credential)109 .vaultUrl(CONFIGURATION.get(AZURE_VAULT_URL))110 .buildClient();111 KeyVaultSecret secret = client.getSecret(VAULT_SECRET_NAME);112 Assert.assertNotNull(secret);113 Assert.assertEquals(VAULT_SECRET_NAME, secret.getName());114 Assert.assertNotNull(secret.getValue());115 }116 @Test117 public void testIMDSEndpointWithUserAssigned() throws Exception {118 org.junit.Assume.assumeTrue(checkIMDSAvailable());119 org.junit.Assume.assumeNotNull(CONFIGURATION.get(Configuration.PROPERTY_AZURE_CLIENT_ID));120 org.junit.Assume.assumeNotNull(CONFIGURATION.get(AZURE_VAULT_URL));121 IdentityClient client = new IdentityClientBuilder()122 .clientId(CONFIGURATION.get(Configuration.PROPERTY_AZURE_CLIENT_ID))123 .build();124 StepVerifier.create(client.authenticateToIMDSEndpoint(125 new TokenRequestContext().addScopes("https://management.azure.com/.default")))126 .expectNextMatches(accessToken -> accessToken != null && accessToken.getToken() != null)127 .verifyComplete();128 }129 @Test130 public void testIMDSEndpointWithUserAssignedAccessKeyVault() throws Exception {131 org.junit.Assume.assumeTrue(checkIMDSAvailable());132 org.junit.Assume.assumeNotNull(CONFIGURATION.get(Configuration.PROPERTY_AZURE_CLIENT_ID));133 org.junit.Assume.assumeNotNull(CONFIGURATION.get(AZURE_VAULT_URL));134 ManagedIdentityCredential credential = new ManagedIdentityCredentialBuilder()135 .clientId(CONFIGURATION.get(Configuration.PROPERTY_AZURE_CLIENT_ID))136 .build();137 SecretClient client = new SecretClientBuilder()138 .credential(credential)139 .vaultUrl(CONFIGURATION.get(AZURE_VAULT_URL))140 .buildClient();141 KeyVaultSecret secret = client.getSecret(VAULT_SECRET_NAME);142 Assert.assertNotNull(secret);143 Assert.assertEquals(VAULT_SECRET_NAME, secret.getName());144 Assert.assertNotNull(secret.getValue());145 }146 private boolean checkIMDSAvailable() {147 StringBuilder payload = new StringBuilder();...
Source:AssumptionTest.java
2import static org.hamcrest.CoreMatchers.is;3import static org.junit.Assert.assertThat;4import static org.junit.Assert.fail;5import static org.junit.Assume.assumeNoException;6import static org.junit.Assume.assumeNotNull;7import static org.junit.Assume.assumeThat;8import static org.junit.Assume.assumeTrue;9import static org.junit.experimental.results.PrintableResult.testResult;10import static org.junit.experimental.results.ResultMatchers.isSuccessful;11import static org.junit.internal.matchers.StringContains.containsString;12import org.junit.Assume;13import org.junit.Before;14import org.junit.BeforeClass;15import org.junit.Test;16import org.junit.internal.AssumptionViolatedException;17import org.junit.runner.JUnitCore;18import org.junit.runner.Result;19import org.junit.runner.notification.Failure;20import org.junit.runner.notification.RunListener;21public class AssumptionTest {22 public static class HasFailingAssumption {23 @Test24 public void assumptionsFail() {25 assumeThat(3, is(4));26 fail();27 }28 }29 @Test30 public void failedAssumptionsMeanPassing() {31 Result result= JUnitCore.runClasses(HasFailingAssumption.class);32 assertThat(result.getRunCount(), is(1));33 assertThat(result.getIgnoreCount(), is(0));34 assertThat(result.getFailureCount(), is(0));35 }36 private static int assumptionFailures= 0;37 @Test38 public void failedAssumptionsCanBeDetectedByListeners() {39 assumptionFailures= 0;40 JUnitCore core= new JUnitCore();41 core.addListener(new RunListener() {42 @Override43 public void testAssumptionFailure(Failure failure) {44 assumptionFailures++;45 }46 });47 core.run(HasFailingAssumption.class);48 49 assertThat(assumptionFailures, is(1));50 }51 public static class HasPassingAssumption {52 @Test53 public void assumptionsFail() {54 assumeThat(3, is(3));55 fail();56 }57 }58 @Test59 public void passingAssumptionsScootThrough() {60 Result result= JUnitCore.runClasses(HasPassingAssumption.class);61 assertThat(result.getRunCount(), is(1));62 assertThat(result.getIgnoreCount(), is(0));63 assertThat(result.getFailureCount(), is(1));64 }65 @Test(expected= AssumptionViolatedException.class)66 public void assumeThatWorks() {67 assumeThat(1, is(2));68 }69 @Test70 public void assumeThatPasses() {71 assumeThat(1, is(1));72 assertCompletesNormally();73 }74 @Test75 public void assumeThatPassesOnStrings() {76 assumeThat("x", is("x"));77 assertCompletesNormally();78 }79 @Test(expected= AssumptionViolatedException.class)80 public void assumeNotNullThrowsException() {81 Object[] objects= { 1, 2, null };82 assumeNotNull(objects);83 }84 @Test85 public void assumeNotNullPasses() {86 Object[] objects= { 1, 2 };87 assumeNotNull(objects);88 assertCompletesNormally();89 }90 @Test91 public void assumeNotNullIncludesParameterList() {92 try {93 Object[] objects= { 1, 2, null };94 assumeNotNull(objects);95 } catch (AssumptionViolatedException e) {96 assertThat(e.getMessage(), containsString("1, 2, null"));97 } catch (Exception e) {98 fail("Should have thrown AssumptionViolatedException");99 }100 }101 @Test102 public void assumeNoExceptionThrows() {103 final Throwable exception= new NullPointerException();104 try {105 assumeNoException(exception);106 fail("Should have thrown exception");107 } catch (AssumptionViolatedException e) {108 assertThat(e.getCause(), is(exception));...
Source:TestTwitterSource.java
...42public class TestTwitterSource extends Assert {43 @BeforeClass44 public static void setUp() {45 try {46 Assume.assumeNotNull(InetAddress.getByName("stream.twitter.com"));47 } catch (UnknownHostException e) {48 Assume.assumeTrue(false); // ignore Test if twitter is unreachable49 }50 }51 52 @Test53 public void testBasic() throws Exception {54 String consumerKey = System.getProperty("twitter.consumerKey");55 Assume.assumeNotNull(consumerKey);56 String consumerSecret = System.getProperty("twitter.consumerSecret");57 Assume.assumeNotNull(consumerSecret);58 String accessToken = System.getProperty("twitter.accessToken");59 Assume.assumeNotNull(accessToken);60 String accessTokenSecret = System.getProperty("twitter.accessTokenSecret");61 Assume.assumeNotNull(accessTokenSecret);62 Context context = new Context();63 context.put("consumerKey", consumerKey);64 context.put("consumerSecret", consumerSecret);65 context.put("accessToken", accessToken);66 context.put("accessTokenSecret", accessTokenSecret);67 context.put("maxBatchDurationMillis", "1000");68 TwitterSource source = new TwitterSource();69 source.configure(context);70 Map<String, String> channelContext = new HashMap();71 channelContext.put("capacity", "1000000");72 channelContext.put("keep-alive", "0"); // for faster tests73 Channel channel = new MemoryChannel();74 Configurables.configure(channel, new Context(channelContext));75 Sink sink = new LoggerSink();...
Source:PerformanceHintManagerTest.java
...18import static org.junit.Assert.assertNotEquals;19import static org.junit.Assert.assertNull;20import static org.junit.Assert.assertThrows;21import static org.junit.Assert.assertTrue;22import static org.junit.Assume.assumeNotNull;23import android.os.PerformanceHintManager.Session;24import androidx.test.InstrumentationRegistry;25import androidx.test.runner.AndroidJUnit4;26import org.junit.Before;27import org.junit.Test;28import org.junit.runner.RunWith;29import org.mockito.Mock;30import org.mockito.MockitoAnnotations;31@RunWith(AndroidJUnit4.class)32public class PerformanceHintManagerTest {33 private static final long RATE_1000 = 1000L;34 private static final long TARGET_166 = 166L;35 private static final long DEFAULT_TARGET_NS = 16666666L;36 private PerformanceHintManager mPerformanceHintManager;37 @Mock38 private IHintSession mIHintSessionMock;39 @Before40 public void setUp() {41 mPerformanceHintManager =42 InstrumentationRegistry.getInstrumentation().getContext().getSystemService(43 PerformanceHintManager.class);44 MockitoAnnotations.initMocks(this);45 }46 private Session createSession() {47 return mPerformanceHintManager.createHintSession(48 new int[]{Process.myPid()}, DEFAULT_TARGET_NS);49 }50 @Test51 public void testCreateHintSession() {52 Session a = createSession();53 Session b = createSession();54 if (a == null) {55 assertNull(b);56 } else {57 assertNotEquals(a, b);58 }59 }60 @Test61 public void testGetPreferredUpdateRateNanos() {62 if (createSession() != null) {63 assertTrue(mPerformanceHintManager.getPreferredUpdateRateNanos() > 0);64 } else {65 assertEquals(-1, mPerformanceHintManager.getPreferredUpdateRateNanos());66 }67 }68 @Test69 public void testUpdateTargetWorkDuration() {70 Session s = createSession();71 assumeNotNull(s);72 s.updateTargetWorkDuration(100);73 }74 @Test75 public void testUpdateTargetWorkDurationWithNegativeDuration() {76 Session s = createSession();77 assumeNotNull(s);78 assertThrows(IllegalArgumentException.class, () -> {79 s.updateTargetWorkDuration(-1);80 });81 }82 @Test83 public void testReportActualWorkDuration() {84 Session s = createSession();85 assumeNotNull(s);86 s.updateTargetWorkDuration(100);87 s.reportActualWorkDuration(1);88 s.reportActualWorkDuration(100);89 s.reportActualWorkDuration(1000);90 }91 @Test92 public void testReportActualWorkDurationWithIllegalArgument() {93 Session s = createSession();94 assumeNotNull(s);95 s.updateTargetWorkDuration(100);96 assertThrows(IllegalArgumentException.class, () -> {97 s.reportActualWorkDuration(-1);98 });99 }100 @Test101 public void testCloseHintSession() {102 Session s = createSession();103 assumeNotNull(s);104 s.close();105 }106}...
Source:UsersTest.java
...6import org.junit.experimental.theories.Theory;7import org.junit.rules.ExpectedException;8import org.junit.runner.RunWith;9import static org.hamcrest.CoreMatchers.*;10import static org.junit.Assume.assumeNotNull;11import static org.junit.Assume.assumeThat;12@RunWith(Theories.class)13public class UsersTest {14 private static User user1;15 private static User user2;16 @Rule17 public ExpectedException thrown = ExpectedException.none();18 @BeforeClass19 public static void createUsers() {20 user1 = new User("Nataliya", "svk", 56646, "56452ghh54");21 user2 = new User("Alexander", "kim", 46843, "54746jm458");22 }23 @DataPoints24 public static String[] usersNames() {25 return new String[]{user1.getName(), user2.getName()};26 }27 @Theory28 public void testUsersNames(String name) throws Exception {29 System.out.println(String.format("Testing with name %s and login %s", name));30 assumeNotNull(name);31 assumeThat(name, notNullValue());32 }33 @DataPoints34 public static String[] usersLogin() {35 return new String[]{user1.getLogin(), user2.getLogin()};36 }37 @Theory38 public void testUsersLogin(String login) throws Exception {39 System.out.println(String.format("Testing with login %s ", login));40 assumeNotNull(login);41 assumeThat(login, notNullValue());42 }43 @DataPoints44 public static int[] usersPassword() {45 return new int[]{(int) user1.getPassword(), (int) user2.getPassword()};46 }47 @Theory48 public void testUsersPassword(int password) throws Exception {49 System.out.println(String.format("Testing with password %d ", password));50 assumeNotNull(password);51 assumeThat(password, notNullValue());52 }53}...
Source:UsingAssume.java
1package com.acme.example.time;2import static org.hamcrest.Matchers.greaterThan;3import static org.junit.Assert.assertNotNull;4import static org.junit.Assert.assertThat;5import static org.junit.Assume.assumeNotNull;6import java.util.Date;7import org.junit.Test;8import org.junit.runner.RunWith;9import org.springframework.beans.factory.annotation.Autowired;10import org.springframework.test.context.ContextConfiguration;11import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;12import org.springframework.transaction.annotation.Transactional;13import com.acme.example.config.AppContext;14@RunWith(SpringJUnit4ClassRunner.class)15@ContextConfiguration(classes = { AppContext.class })16@Transactional17public class UsingAssume {18 @Autowired19 private RecordRepository repo;20 21 @Autowired22 private RecordService service;23 @Test24 public void badTestThatTestsAllAspectsAtOnce() {25 Record recordToSave = new Record(new Date(), new Date());26 27 Record record = service.saveRecord(recordToSave);28 assertNotNull(record);29 assertNotNull(record.getId());30 31 assertThat(record.getId(), greaterThan(0L));32 }33 34 @Test35 public void saveRecordDoesNotReturnNullWhenSavingAValidRecord() {36 Record validRecord = new Record(new Date(), new Date());37 38 Record record = service.saveRecord(validRecord);39 40 assertNotNull(record);41 }42 @Test43 public void saveRecordCreatesANonNullIdWhenSavingAValidRecord() {44 Record validRecord = new Record(new Date(), new Date());45 46 Record record = service.saveRecord(validRecord);47 48 assumeNotNull(record);49 assertNotNull(record.getId());50 }51 @Test52 public void saveRecordCreatesAnIdGreaterThanZeroWhenSavingAValidRecord() {53 Record recordToSave = new Record(new Date(), new Date());54 55 Record record = service.saveRecord(recordToSave);56 assumeNotNull(record);57 assumeNotNull(record.getId());58 59 assertThat(record.getId(), greaterThan(0L));60 }61 62}
Source:ObjectContractTest.java
1package org.junit.tests;2import static org.hamcrest.CoreMatchers.is;3import static org.junit.Assert.assertThat;4import static org.junit.Assume.assumeNotNull;5import static org.junit.Assume.assumeThat;6import java.lang.reflect.Method;7import org.junit.Test;8import org.junit.Test.None;9import org.junit.experimental.theories.DataPoints;10import org.junit.experimental.theories.Theories;11import org.junit.experimental.theories.Theory;12import org.junit.runner.RunWith;13import org.junit.runners.model.FrameworkMethod;14@RunWith(Theories.class)15public class ObjectContractTest {16 @DataPoints17 public static Object[] objects= { new FrameworkMethod(toStringMethod()),18 new FrameworkMethod(toStringMethod()), 3, null };19 @Theory20 @Test(expected= None.class)21 public void equalsThrowsNoException(Object a, Object b) {22 assumeNotNull(a);23 a.equals(b);24 }25 @Theory26 public void equalsMeansEqualHashCodes(Object a, Object b) {27 assumeNotNull(a, b);28 assumeThat(a, is(b));29 assertThat(a.hashCode(), is(b.hashCode()));30 }31 private static Method toStringMethod() {32 try {33 return Object.class.getMethod("toString");34 } catch (SecurityException e) {35 } catch (NoSuchMethodException e) {36 }37 return null;38 }39}...
assumeNotNull
Using AI Code Generation
1public class JUnit5AssumptionsTest {2 void testOnlyOnCiServer() {3 assumeTrue("CI".equals(System.getenv("ENV")));4 }5 void testOnlyOnDeveloperWorkstation() {6 assumeTrue("DEV".equals(System.getenv("ENV")),7 () -> "Aborting test: not on developer workstation");8 }9 void testInAllEnvironments() {10 assumingThat("CI".equals(System.getenv("ENV")),11 () -> {12 assertEquals(2, 2);13 });14 assertEquals("a string", "a string");15 }16}
assumeNotNull
Using AI Code Generation
1public void testAssumeNotNull() {2 assumeNotNull(new Object());3}4public void testAssumeTrue() {5 assumeTrue(2 > 1);6}7public void testAssumeFalse() {8 assumeFalse(1 > 2);9}10public void testAssumeNoException() {11 try {12 } catch (Exception e) {13 assumeNoException(e);14 }15}16public void testFail() {17 fail();18}19public void testFailWithMessage() {20 fail("Test failed");21}22public void testAssertArrayEquals() {23 int[] expected = {1, 2, 3};24 int[] actual = {1, 2, 3};25 assertArrayEquals(expected, actual);26}27public void testAssertEquals() {28 String expected = "test";29 String actual = "test";30 assertEquals(expected, actual);31}32public void testAssertEqualsWithDelta() {33 double expected = 0.1;34 double actual = 0.1;35 assertEquals(expected, actual, 0.01);36}37public void testAssertEqualsWithMessage() {38 String expected = "test";39 String actual = "test";40 assertEquals("assertion
assumeNotNull
Using AI Code Generation
1public void testAssumeNotNull() {2 String str = null;3 assumeNotNull(str);4 fail("test should have been skipped");5}6public void testAssumeTrue() {7 assumeTrue(false);8 fail("test should have been skipped");9}10public void testAssumeFalse() {11 assumeFalse(true);12 fail("test should have been skipped");13}14public void testAssumeNoException() {15 assumeNoException(new RuntimeException("test"));16 fail("test should have been skipped");17}18public void testAssumeNoException2() {19 assumeNoException(new RuntimeException("test"));20 fail("test should have been skipped");21}22public void testAssumeNoException3() {23 assumeNoException(new RuntimeException("test"));24 fail("test should have been skipped");25}26public void testAssumeNoException4() {27 assumeNoException(new RuntimeException("test"));28 fail("test should have been skipped");29}30public void testAssumeNoException5() {31 assumeNoException(new RuntimeException("test"));32 fail("test should have been skipped");33}34public void testAssumeNoException6() {35 assumeNoException(new RuntimeException("test"));36 fail("test should have been skipped");37}
LambdaTest also has a detailed JUnit tutorial explaining its features, importance, advanced use cases, best practices, and more to help you get started with running your automation testing scripts.
Here are the detailed JUnit testing chapters to help you get started:
You can also check out our JUnit certification if you wish to take your career in Selenium automation testing with JUnit to the next level.
Get 100 minutes of automation test minutes FREE!!