8wDlpd.png
8wDFp9.png
8wDEOx.png
8wDMfH.png
8wDKte.png

在 flutter_map 上查看 Geojson

darren 2月前

58 0

我想在地图上显示 Geojson 数据来绘制多边形和点我使用了 Flutter_map 库:^4.0.0我尝试从 geojson 转换为 latlng 但没有找到方法应该有帮助的库......

我想在地图上显示 Geojson 数据来绘制多边形和点我使用了 Flutter_map 库:^4.0.0

我尝试将 geojson 转换为 latlng,但没有找到方法应该对我有帮助的库都很旧了

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [longitude, latitude]
      },
      "properties": {
        "name": "point name",
        "description": "point desc"
      }
    }
  ]
}
帖子版权声明 1、本帖标题:在 flutter_map 上查看 Geojson
    本站网址:http://xjnalaquan.com/
2、本网站的资源部分来源于网络,如有侵权,请联系站长进行删除处理。
3、会员发帖仅代表会员个人观点,并不代表本站赞同其观点和对其真实性负责。
4、本站一律禁止以任何方式发布或转载任何违法的相关信息,访客发现请向站长举报
5、站长邮箱:yeweds@126.com 除非注明,本帖由darren在本站《dictionary》版块原创发布, 转载请注明出处!
最新回复 (0)
  • 以下是示例代码,您可以根据需要进行更改:

    我使用这 3 个包:
    • flutter_map
    • 地理编码
    • latlong2
    样本结果

    enter image description here

    示例代码
    • 应用程序加载时,它会显示地图标记
    • 单击每个标记以显示其标签
    import 'package:flutter/material.dart';
    import 'package:flutter_map/flutter_map.dart';
    import 'package:geojson/geojson.dart';
    import 'package:latlong2/latlong.dart';
    
    void main() {
      runApp(const MyApp());
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({Key? key}) : super(key: key);
    
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter App!!',
          theme: ThemeData(
            colorSchemeSeed: Colors.indigo,
            useMaterial3: true,
            brightness: Brightness.light,
          ),
          darkTheme: ThemeData(
            colorSchemeSeed: Colors.blue,
            useMaterial3: true,
            brightness: Brightness.dark,
          ),
          home: const MyHomePage(title: 'Flutter Example App'),
          debugShowCheckedModeBanner: false,
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      const MyHomePage({Key? key, required this.title}): super(key: key);
    
      final String title;
    
      @override
      State<MyHomePage> createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
    
      List<GeoJsonFeature<dynamic>>? data;
    
      @override
        void initState() {
          WidgetsBinding.instance.addPostFrameCallback((_) {
            loadGeoJsonFeatureFromGeoJson().whenComplete(() {
              setState(() {
                print('Completed');
              });
            });
          });
          super.initState();
        }
    
      @override
      Widget build(BuildContext context) {
    
        List<Polyline> _polylines = [];
        List<Marker> _markers = [];
        
        if (data != null) { 
          data!.forEach((data) {
            if (data.type == GeoJsonFeatureType.line) {
              GeoJsonLine line = data.geometry;
              final poly = Polyline(points: line.geoSerie!.toLatLng(), color: Colors.blue, strokeWidth: 5);
              _polylines.add(poly);
              // lines.add(data.geometry);
            } else if (data.type == GeoJsonFeatureType.point) {
              GeoJsonPoint point = data.geometry;
              final marker = Marker(
                point: point.geoPoint.toLatLng()!, 
                width: 20, 
                height: 20, 
                builder: (context) => Tooltip(
                  message: data.properties?['STATIONNAME'] ?? '',
                  triggerMode: TooltipTriggerMode.tap,
                  child: Container(
                    decoration: BoxDecoration(
                      color: Colors.deepPurple,
                      borderRadius: BorderRadius.circular(99),
                    ),
                  ),
                ),
              );
              _markers.add(marker);
            }
            // Add more features
          });
    
        }
    
        return Scaffold(
          appBar: AppBar(
            title: Text(widget.title),
          ),
          body: SizedBox(
            width: MediaQuery.of(context).size.width,
            height: MediaQuery.of(context).size.height,
            child: FlutterMap(
              options: MapOptions(
                center: LatLng(38.897283, -77.021918),
                zoom: 12,
              ),
              children: [
                TileLayer(
                  urlTemplate: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', 
                  subdomains: const <String>['a', 'b', 'c',], 
                ),
                MarkerLayer(markers: _markers),
                // PolylineLayer(polylines: _polylines),
              ],
            ),
          ),
        );
      }
    
      Future<List<GeoJsonFeature>?> loadGeoJsonFeatureFromGeoJson() async {
        try {
          String geoJsonBikeLocation = '''
            {
              "type": "FeatureCollection",
              "features": [
                  {
                      "type": "Feature",
                      "properties": {
                          "OBJECTID": 1,
                          "LOCATIONID": 3,
                          "STATIONNAME": "Foggy Bottom",
                          "BIKECOUNT": 9,
                          "ADDRESS": "23rd St & I St",
                          "QUADRANT": "NW",
                          "WEB_URL": "https://www.smartbikedc.com/",
                          "PHONE": "1-800-899-4449"
                      },
                      "geometry": {
                          "type": "Point",
                          "coordinates": [
                              -77.05012628095922,
                              38.901405158996035
                          ]
                      }
                  },
                  {
                      "type": "Feature",
                      "properties": {
                          "OBJECTID": 2,
                          "LOCATIONID": 1,
                          "STATIONNAME": "Dupont Circle",
                          "BIKECOUNT": 15,
                          "ADDRESS": "Massachusetts Ave & Dupont Cir",
                          "QUADRANT": "NW",
                          "WEB_URL": "https://www.smartbikedc.com/",
                          "PHONE": "1-800-899-4449"
                      },
                      "geometry": {
                          "type": "Point",
                          "coordinates": [
                              -77.04434905357506,
                              38.91018149756077
                          ]
                      }
                  },
                  {
                      "type": "Feature",
                      "properties": {
                          "OBJECTID": 3,
                          "LOCATIONID": 4,
                          "STATIONNAME": "Gallery Place",
                          "BIKECOUNT": 15,
                          "ADDRESS": "7th St & F St",
                          "QUADRANT": "NW",
                          "WEB_URL": "https://www.smartbikedc.com/",
                          "PHONE": "1-800-899-4449"
                      },
                      "geometry": {
                          "type": "Point",
                          "coordinates": [
                              -77.02191815762689,
                              38.89728344626466
                          ]
                      }
                  },
                  {
                      "type": "Feature",
                      "properties": {
                          "OBJECTID": 4,
                          "LOCATIONID": 7,
                          "STATIONNAME": "McPherson Square",
                          "BIKECOUNT": 8,
                          "ADDRESS": "14th St & H St",
                          "QUADRANT": "NW",
                          "WEB_URL": "https://www.smartbikedc.com/",
                          "PHONE": "1-800-899-4449"
                      },
                      "geometry": {
                          "type": "Point",
                          "coordinates": [
                              -77.03240717405485,
                              38.90078499892696
                          ]
                      }
                  },
                  {
                      "type": "Feature",
                      "properties": {
                          "OBJECTID": 5,
                          "LOCATIONID": 9,
                          "STATIONNAME": "Reeves Center",
                          "BIKECOUNT": 12,
                          "ADDRESS": "14th St & U St",
                          "QUADRANT": "NW",
                          "WEB_URL": "https://www.smartbikedc.com/",
                          "PHONE": "1-800-899-4449"
                      },
                      "geometry": {
                          "type": "Point",
                          "coordinates": [
                              -77.03248214713554,
                              38.917373230883015
                          ]
                      }
                  },
                  {
                      "type": "Feature",
                      "properties": {
                          "OBJECTID": 6,
                          "LOCATIONID": 10,
                          "STATIONNAME": "Shaw",
                          "BIKECOUNT": 15,
                          "ADDRESS": "7th St & T St",
                          "QUADRANT": "NW",
                          "WEB_URL": "https://www.smartbikedc.com/",
                          "PHONE": "1-800-899-4449"
                      },
                      "geometry": {
                          "type": "Point",
                          "coordinates": [
                              -77.02191245663357,
                              38.91598834308168
                          ]
                      }
                  },
                  {
                      "type": "Feature",
                      "properties": {
                          "OBJECTID": 7,
                          "LOCATIONID": 8,
                          "STATIONNAME": "Metro Center",
                          "BIKECOUNT": 8,
                          "ADDRESS": "12th St & G St",
                          "QUADRANT": "NW",
                          "WEB_URL": "https://www.smartbikedc.com/",
                          "PHONE": "1-800-899-4449"
                      },
                      "geometry": {
                          "type": "Point",
                          "coordinates": [
                              -77.02848392960873,
                              38.8987482181005
                          ]
                      }
                  },
                  {
                      "type": "Feature",
                      "properties": {
                          "OBJECTID": 8,
                          "LOCATIONID": 5,
                          "STATIONNAME": "Judiciary Square",
                          "BIKECOUNT": 8,
                          "ADDRESS": "4th St & E St",
                          "QUADRANT": "NW",
                          "WEB_URL": "https://www.smartbikedc.com/",
                          "PHONE": "1-800-899-4449"
                      },
                      "geometry": {
                          "type": "Point",
                          "coordinates": [
                              -77.01540042306134,
                              38.89574098950278
                          ]
                      }
                  },
                  {
                      "type": "Feature",
                      "properties": {
                          "OBJECTID": 9,
                          "LOCATIONID": 6,
                          "STATIONNAME": "Logan Circle",
                          "BIKECOUNT": 12,
                          "ADDRESS": "14th St & Rhode Island Ave",
                          "QUADRANT": "NW",
                          "WEB_URL": "https://www.smartbikedc.com/",
                          "PHONE": "1-800-899-4449"
                      },
                      "geometry": {
                          "type": "Point",
                          "coordinates": [
                              -77.03219558571061,
                              38.90855656831227
                          ]
                      }
                  },
                  {
                      "type": "Feature",
                      "properties": {
                          "OBJECTID": 10,
                          "LOCATIONID": 2,
                          "STATIONNAME": "Farragut Square",
                          "BIKECOUNT": 15,
                          "ADDRESS": "17th St & K St",
                          "QUADRANT": "NW",
                          "WEB_URL": "https://www.smartbikedc.com/",
                          "PHONE": "1-800-899-4449"
                      },
                      "geometry": {
                          "type": "Point",
                          "coordinates": [
                              -77.03788324789845,
                              38.90220976421636
                          ]
                      }
                  }
              ]
          }
          ''';
    
          final geojson = GeoJson();
          await geojson.parse(geoJsonBikeLocation);
    
          data = geojson.features;
        } catch (e) {
          print(e.toString);
          rethrow;
        }
        return data;
    
      }
    
    }
    
  • Python 版本:3.9.6def test_chunked_upload():\'\'\'可以安全地发送生成器\'\'\' close_server = threading.Event() server = Server.basic_response_server(

    Python版本:3.9.6

    def test_chunked_upload():
    """can safely send generators"""
     close_server = threading.Event()
     server = Server.basic_response_server(wait_to_close_event=close_server)
     data = iter([b"a", b"b", b"c"])
    
     with server as (host, port):
     url = f"http://{host}:{port}/"
     r = requests.post(url, data=data, stream=True)
     close_server.set()  # release server block
    
     >       assert r.status_code == 200
     E       assert 502 == 200
     E        +  where 502 = <Response [502]>.status_code
     
     tests/test_lowlevel.py:35: AssertionError
    
    

    构建命令:python3 -u -m build -wTest 命令:tox -e py39-default

    我正在 Docker 容器中构建它。有人能指出为什么会发生这种情况吗?

  • 我的目标是学习一些关于在 Jersey Test 上下文中模拟对象的知识。我有 3 个类:ServiceControllerpackage com.vogella.jersey.first;import javax.ws.rs.*;import javax.ws.rs....

    我的目标是学习一些关于在 Jersey Test 环境中模拟对象的知识。我有 3 个类:

    服务控制器

    package com.vogella.jersey.first;
    
    import javax.ws.rs.*;
    import javax.ws.rs.ext.Provider;
    
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    
    public class ServiceController {
    
        private static Log log = LogFactory.getLog(ServiceController.class);
    
        public String returnSth(String inSth) {
            return "returned RET" + inSth;
        }
    
    }
    

    你好

    package com.vogella.jersey.first;
    
    import javax.inject.Inject;
    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.Produces;
    import javax.ws.rs.core.MediaType;
    
    @Path("/hello")
    public class Hello {
    
        @Inject
        private ServiceController serviceController;
    
        private String inStr = "BLA";
    
        @GET
        @Produces(MediaType.TEXT_PLAIN)
        public String sayPlainTextHello() {
            return "Hello Jersey" + serviceController.returnSth(inStr);
        }
    
        @GET
        @Produces(MediaType.TEXT_XML)
        public String sayXMLHello() {
            return "<?xml version=\"1.0\"?>" + "<hello> Hello Jersey" + "</hello>";
        }
    
        @GET
        @Produces(MediaType.TEXT_HTML)
        public String sayHtmlHello() {
            return "<html> " + "<title>" + "Hello Jersey" + "</title>"
                    + "<body><h1>" + "Hello Jersey" + serviceController.returnSth(inStr) + "</body></h1>" + "</html> ";
        }
    
    } 
    

    测试

    package com.vogella.jersey.first;
    
    import org.glassfish.hk2.utilities.binding.AbstractBinder;
    import org.glassfish.jersey.server.ResourceConfig;
    import org.glassfish.jersey.test.JerseyTest;
    import org.junit.jupiter.api.Test;
    
    import javax.ws.rs.core.Application;
    import javax.ws.rs.core.MediaType;
    import javax.ws.rs.core.Response;
    
    import static junit.framework.Assert.assertEquals;
    import static junit.framework.Assert.assertTrue;
    import static org.mockito.Mockito.*;
    
    class HelloTest extends JerseyTest {
    
        private ServiceController serviceController;
    
        @Override
        protected Application configure() {
            ResourceConfig config = new ResourceConfig(Hello.class);
            serviceController = mock(ServiceController.class);
            config.register(new AbstractBinder() {
                @Override
                protected void configure() {
                    bind(ServiceController.class).to(ServiceController.class);
                }
            }
            );
            return config;
        }
    
        @Test
        public void helloResponseCodeOK() {
            Response response = target("hello").request()
                    .get();
    
            assertEquals("Http Response should be 200: ", Response.Status.OK.getStatusCode(), response.getStatus());
    
        }
    
        @Test
        public void helloResponseTextIsCorrect() {
            when(serviceController.returnSth(any(String.class))).thenReturn("RetFromMock");
    
            Response response = target("hello").request(MediaType.TEXT_PLAIN)
                    .get();
    
            assertTrue("Hello Jerseyreturned RETBLA".equals(response.readEntity(String.class)));
    
        }
    
    }
    

    因此,在 Hello 类中有一个 \'hello\' 端点,并且在 2 个方法中从注入的 ServiceController 调用了一个 \'returnSth\' 方法。

    在 HelloTest 中,我想测试 \'hello\' 端点,但不调用真正的 serviceController.returnSth 方法 - 而是想模拟它并返回一些其他字符串 - \'RetFromMock\',无论输入如何。

    但是在测试执行期间,模拟无效,并且仍然调用真正的模拟。我预计 assertTrue 会失败,因为如果模拟被调用,响应输出应该是 \'Hello JerseyRetFromMock\',但始终是 \'Hello Jerseyreturned RETBLA\'。

    我尝试了不同的方式来实例化模拟:

    注射:

    @Inject
    private ServiceController serviceController;
    

    使用注释进行模拟:

    @Mock
    private ServiceController serviceController;
    
    @InjectMocks
    private ServiceController serviceController;
    

    这些尝试导致了 NullPointerException(serviceController 为空)。上面我还尝试使用 @RunWith(MockitoJUnitRunner.class) 注释,结果相同。

    我也尝试按照此链接中的示例进行操作: https://medium.com/@mnu/overriding-dependency-injection-with-hk2-in-jersey-tests-4756144c2399

    但从未能使 \'bind(serviceController).to(ServiceController.class)\' 工作 - 因 IllegalArgumentException 而失败。

    =============================在评论中与@knittl 进行几次迭代后进行编辑

    目前 HelloTest 如下所示:

    package com.vogella.jersey.first;
    
    import org.glassfish.hk2.utilities.binding.AbstractBinder;
    import org.glassfish.jersey.server.ResourceConfig;
    import org.glassfish.jersey.test.JerseyTest;
    import org.junit.jupiter.api.BeforeEach;
    import org.junit.jupiter.api.Test;
    import org.mockito.InjectMocks;
    import org.mockito.MockitoAnnotations;
    
    import javax.ws.rs.core.Application;
    import javax.ws.rs.core.MediaType;
    import javax.ws.rs.core.Response;
    
    import static junit.framework.Assert.assertEquals;
    import static junit.framework.Assert.assertTrue;
    import static org.mockito.Mockito.*;
    
    class HelloTest extends JerseyTest {
    
        @BeforeEach
        public void init() {
            MockitoAnnotations.openMocks(this);
        }
    
        @InjectMocks
        private ServiceController serviceController;
    
        @Override
        protected Application configure() {
            ResourceConfig config = new ResourceConfig(Hello.class);
            //serviceController = mock(ServiceController.class);
            config.register(new AbstractBinder() {
                @Override
                protected void configure() {
                    bind(ServiceController.class).to(ServiceController.class);
                }
            }
            );
            return config;
        }
    
        @Test
        public void helloResponseCodeOK() {
            Response response = target("hello").request()
                    .get();
    
            assertEquals("Http Response should be 200: ", Response.Status.OK.getStatusCode(), response.getStatus());
    
        }
    
        @Test
        public void helloResponseTextIsCorrect() {
            //configure();
    
            when(serviceController.returnSth(any(String.class))).thenReturn("RetFromMock");
    
            Response response = target("hello").request(MediaType.TEXT_PLAIN)
                    .get();
    
            assertTrue("Hello Jerseyreturned RETBLA".equals(response.readEntity(String.class)));
    
        }
    
    }
    

    并获取指向包含“when thenReturn”行的行“HelloTest.helloResponseTextIsCorrect:64 InvalidUseOfMatchers”。

  • 我的功能测试使用 Microsoft.EntityFrameworkCore.InMemory 版本 7.0.20。当我对任何具有 dateonly 字段的实体运行功能测试时,出现错误:类型为“System”的表达式。

    我的功能测试使用 Microsoft.EntityFrameworkCore.InMemory 版本 7.0.20。

    当我对任何具有 dateonly 字段的实体运行功能测试时,出现错误:

    类型为“System.Nullable`1[System.DateOnly]”的表达式不能用于方法“System.DateOnly FromDateTime(System.DateTime)”(参数“arg0”)类型为“System.DateTime”的参数

    我用的是这个 DateOnlyConverter

    public class DateOnlyConverter : ValueConverter<DateOnly, DateTime>
    {
        /// <summary>
        /// Creates a new instance of this converter.
        /// </summary>
        public DateOnlyConverter() : base(
            d => d.ToDateTime(TimeOnly.MinValue),
            d => DateOnly.FromDateTime(d))
        { }
    }
    

    这是实体配置:

    public void Configure(EntityTypeBuilder<Payback> builder)
    {
        builder.ToTable("Paybacks").HasKey(k => k.Id);
    
        // other properties
    
        builder
          .OwnsOne(p => p.CurrentPaybackSchedule, s =>
          {
            s.WithOwner();
            s.Property(s => s.ScheduleDate).HasConversion<DateOnlyConverter>().HasColumnName(nameof(Payback.CurrentPaybackSchedule.ScheduleDate));
            s.HasIndex(p => p.ScheduleDate);
          });
    }
    

    实体

    public class Payback : BaseEntity<Guid>, IAggregateRoot
    {
    
      //other properties 
    
      public PaybackSchedule CurrentPaybackSchedule { get; private set;}
    
      public Payback()
      {
        //ef
      }
    }
    
    public class PaybackSchedule : ValueObject
    {
      public DateOnly ScheduleDate { get; init; }
      public PaybackScheduleStatus Status { get; private set; }
      public DateTimeOffset TimeEntered { get; private set; }
    
      public PaybackSchedule(DateOnly scheduleDate, PaybackScheduleStatus status)
      {
        ScheduleDate = Guard.Against.Default(scheduleDate, nameof(scheduleDate));
        Status = status;
        TimeEntered = DateTimeOffset.Now;
      }
    
      public PaybackSchedule()
      {
        //ef
      }
    
      public void UpdatePaybackScheduleStatus(PaybackScheduleStatus updatedStatus)
      {
        Status = updatedStatus;
      }
    
      public PaybackSchedule CloneWithRescheduledDate(DateOnly newScheduleDate)
      {
        return new PaybackSchedule(newScheduleDate, Status);
      }
    }
    

    我不确定为什么内存数据库会将该字段作为仅日期字段拉出。

    我检查了所有 EF Core 包的版本,它们似乎都是 v7.0.20。

    当我在功能测试之外运行查询时,代码可以运行。

  • 我对 Java 测试还比较陌生,遇到了一个问题。我即将测试一个 Rest 客户端。我成功测试了所有方法 - put、get、delete。在我为特定目的扩展了我的 delete 方法后...

    我对 Java 测试还比较陌生,遇到了一个问题。我即将测试一个 Rest 客户端。我成功测试了所有方法 - put、get、delete。在我为特定目的扩展了我的删除方法后,我得到了一个无法解决的异常:

    `java.lang.ClassCastException: class io.restassured.response.ValidatableResponseOptions$MockitoMock$Alt0YnEv cannot be cast to class io.restassured.response.ValidatableResponse (io.restassured.response.ValidatableResponseOptions$MockitoMock$Alt0YnEv and io.restassured.response.ValidatableResponse are in unnamed module of loader 'app')`
    

    这是我的代码:

    //要测试的方法

    /**
     * Sends a delete request to given endpoint
     *
     * @param endpoint   Rest endpoint
     * @param parameters valueName=value, valueName2=value2 ... (optional)
     * @return ValidatableResponse
     */
    public ValidatableResponse getJSONResourceDELETE2ArrayParams(String endpoint, String... parameters) {
        if(parameters.length > 1) {
            Response response = given()
                    .cookie(this.cookie)
                    .spec(getJsonRequestSpecification())
                    .params(parameters[0], parameters[1])
                    .when()
                    .delete(this.injectionManager.inject(endpoint));
    
            cookie = extractCookie(response);
    
            return response
                    .then()
                    .statusCode(200);
        } else {
            throw new IllegalArgumentException("This method needs at least two parameter");
        }
    }
    

    // 考试

    private void initRestAssured() {
        restClient.setLogging(RestClient.Logging.ALL);
        mockedRa.when(RestAssured::given).thenReturn(requestSpecification);
        when(requestSpecification.auth().preemptive().basic(anyString(), anyString())
                .multiPart(file)).thenReturn(requestSpecification);
        when(requestSpecification.cookie(cookie)).thenReturn(requestSpecification);
        when(requestSpecification.spec(any())).thenReturn(requestSpecification);
        when(requestSpecification.queryParams(Mockito.any())).thenReturn(requestSpecification);
        when(requestSpecification.when()).thenReturn(requestSpecification);
        when(requestSpecification.get()).thenReturn(response);
        when(requestSpecification.body(Mockito.any(File.class))).thenReturn(requestSpecification);
        when(injectionManager.inject(anyString())).thenReturn("something injected");
        when(requestSpecification.body(anyString())).thenReturn(requestSpecification);
        when(requestSpecification.post("something injected")).thenReturn(response);
        when(response.then()).thenReturn(validatableResponse);
        when(validatableResponse.statusCode(200)).thenReturn(validatableResponse);
        when(validatableResponseOptions.statusCode(200)).thenReturn(validatableResponse);
        when(validatableResponse.contentType(ContentType.JSON)).thenReturn(validatableResponse);
        when(validatableResponse.extract()).thenReturn(extractableResponse);
        when(extractableResponse.response()).thenReturn(response);
        when(response.as(String.class)).thenReturn("returned");
    }
    
    // TODO find issue with Validate Response
    @Test
    void testGetJSONResourceDELETE2ArrayParamsGivenEndPointAndParas_thenDelete() {
        // Given
        initRestAssured();
        String param1 = "id";
        String param2 = "name";
        String[] parameters = new String[2];
        parameters[0] = param1;
        parameters[1] = param2;
    
        // When
        restClient.getJSONResourceDELETE2ArrayParams(endpoint, parameters[0], parameters[1]);
    
        // Then
        verify(injectionManager, times(1)).inject(endpoint);
        verify(requestSpecification, times(1)).delete();
    }
    

    我会很高兴听到任何建议的解决方案:)

  • 嗨,谢谢你的建议。我使用了 MockitoAnnotations.openMocks(this); 并使用 @InjectMocks 注释了 serviceController,现在又出现了另一个异常:HelloTest.helloResponseTextIsCorrect:62 InvalidUseOfMatchers。这指向以下行:when(serviceController.returnSth(any(String.class))).thenReturn(\'RetFromMock\'); 我真的误用了 \'when thenReturn\' 语法吗?目前我不明白是怎么回事。

  • 不幸的是,内存数据库不能保证复制实际 DBMS 的行为,所以我不会用它编写单元测试或集成测试。单元测试应该模拟

  • @knittl 我的意图是将其作为模拟。在核心类“Hello”中,它是一个依赖项,在 HelloTest 中,我想模拟其响应,而不是调用真实的响应。

  • 我已经设置了单元测试来测试代码,这是使用 api 进行的测试。这些测试的一大优势是它们测试数据库查询。模拟数据库将完全减轻测试的这一部分。所以我宁愿不对这些测试这样做。

  • 我无法使用@Import(ExceptionHandler.class)创建bean,我正在尝试使用验证,但是控制器没有获取请求并且邮递员只是返回 400 错误请求,其中...

    我无法使用@Import(ExceptionHandler.class)创建 bean

    我正在尝试使用验证,但控制器没有收到请求,邮递员只是返回 400 个错误请求,而我已经给出了自定义消息来响应 在此处输入图像描述

返回
作者最近主题: